worker_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package miner
  17. import (
  18. "encoding/base64"
  19. "math/big"
  20. "math/rand"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. "github.com/ethereum/go-ethereum/accounts"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/consensus/clique"
  28. "github.com/ethereum/go-ethereum/consensus/ethash"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/mps"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/event"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/private"
  39. "github.com/ethereum/go-ethereum/private/engine"
  40. "github.com/golang/mock/gomock"
  41. "github.com/stretchr/testify/assert"
  42. )
  43. const (
  44. // testCode is the testing contract binary code which will initialises some
  45. // variables in constructor
  46. testCode = "0x60806040527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0060005534801561003457600080fd5b5060fc806100436000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c4dae8814603757806398a213cf146053575b600080fd5b603d607e565b6040518082815260200191505060405180910390f35b607c60048036036020811015606757600080fd5b81019080803590602001909291905050506084565b005b60005481565b806000819055507fe9e44f9f7da8c559de847a3232b57364adc0354f15a2cd8dc636d54396f9587a6000546040518082815260200191505060405180910390a15056fea265627a7a723058208ae31d9424f2d0bc2a3da1a5dd659db2d71ec322a17db8f87e19e209e3a1ff4a64736f6c634300050a0032"
  47. // testGas is the gas required for contract deployment.
  48. testGas = 144109
  49. )
  50. var (
  51. // Test chain configurations
  52. testTxPoolConfig core.TxPoolConfig
  53. ethashChainConfig *params.ChainConfig
  54. cliqueChainConfig *params.ChainConfig
  55. // Test accounts
  56. testBankKey, _ = crypto.GenerateKey()
  57. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  58. testBankFunds = big.NewInt(1000000000000000000)
  59. testUserKey, _ = crypto.GenerateKey()
  60. testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
  61. // Test transactions
  62. pendingTxs []*types.Transaction
  63. newTxs []*types.Transaction
  64. testConfig = &Config{
  65. Recommit: time.Second,
  66. GasFloor: params.GenesisGasLimit,
  67. GasCeil: params.GenesisGasLimit,
  68. }
  69. )
  70. func init() {
  71. testTxPoolConfig = core.DefaultTxPoolConfig
  72. testTxPoolConfig.Journal = ""
  73. ethashChainConfig = params.TestChainConfig
  74. cliqueChainConfig = params.TestChainConfig
  75. cliqueChainConfig.Clique = &params.CliqueConfig{
  76. Period: 10,
  77. Epoch: 30000,
  78. }
  79. signer := types.LatestSigner(params.TestChainConfig)
  80. tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{
  81. ChainID: params.TestChainConfig.ChainID,
  82. Nonce: 0,
  83. To: &testUserAddress,
  84. Value: big.NewInt(1000),
  85. Gas: params.TxGas,
  86. })
  87. pendingTxs = append(pendingTxs, tx1)
  88. tx2 := types.MustSignNewTx(testBankKey, signer, &types.LegacyTx{
  89. Nonce: 1,
  90. To: &testUserAddress,
  91. Value: big.NewInt(1000),
  92. Gas: params.TxGas,
  93. })
  94. newTxs = append(newTxs, tx2)
  95. rand.Seed(time.Now().UnixNano())
  96. }
  97. // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
  98. type testWorkerBackend struct {
  99. db ethdb.Database
  100. txPool *core.TxPool
  101. chain *core.BlockChain
  102. testTxFeed event.Feed
  103. genesis *core.Genesis
  104. uncleBlock *types.Block
  105. }
  106. func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
  107. var gspec = core.Genesis{
  108. Config: chainConfig,
  109. Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
  110. }
  111. switch e := engine.(type) {
  112. case *clique.Clique:
  113. gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength)
  114. copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes())
  115. e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
  116. return crypto.Sign(crypto.Keccak256(data), testBankKey)
  117. })
  118. case *ethash.Ethash:
  119. default:
  120. t.Fatalf("unexpected consensus engine type: %T", engine)
  121. }
  122. genesis := gspec.MustCommit(db)
  123. chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil, nil)
  124. txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain)
  125. // Generate a small n-block chain and an uncle block for it
  126. if n > 0 {
  127. blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, n, func(i int, gen *core.BlockGen) {
  128. gen.SetCoinbase(testBankAddress)
  129. })
  130. if _, err := chain.InsertChain(blocks); err != nil {
  131. t.Fatalf("failed to insert origin chain: %v", err)
  132. }
  133. }
  134. parent := genesis
  135. if n > 0 {
  136. parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash())
  137. }
  138. blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) {
  139. gen.SetCoinbase(testUserAddress)
  140. })
  141. return &testWorkerBackend{
  142. db: db,
  143. chain: chain,
  144. txPool: txpool,
  145. genesis: &gspec,
  146. uncleBlock: blocks[0],
  147. }
  148. }
  149. func (b *testWorkerBackend) ChainDb() ethdb.Database { return b.db }
  150. func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
  151. func (b *testWorkerBackend) TxPool() *core.TxPool { return b.txPool }
  152. func (b *testWorkerBackend) newRandomUncle() *types.Block {
  153. var parent *types.Block
  154. cur := b.chain.CurrentBlock()
  155. if cur.NumberU64() == 0 {
  156. parent = b.chain.Genesis()
  157. } else {
  158. parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
  159. }
  160. blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
  161. var addr = make([]byte, common.AddressLength)
  162. rand.Read(addr)
  163. gen.SetCoinbase(common.BytesToAddress(addr))
  164. })
  165. return blocks[0]
  166. }
  167. func (b *testWorkerBackend) newRandomTx(creation bool, private bool) *types.Transaction {
  168. var signer types.Signer
  169. signer = types.HomesteadSigner{}
  170. if private {
  171. signer = types.QuorumPrivateTxSigner{}
  172. }
  173. var tx *types.Transaction
  174. if creation {
  175. tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, nil, common.FromHex(testCode)), signer, testBankKey)
  176. } else {
  177. tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  178. }
  179. return tx
  180. }
  181. func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
  182. backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
  183. backend.txPool.AddLocals(pendingTxs)
  184. w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
  185. w.setEtherbase(testBankAddress)
  186. return w, backend
  187. }
  188. func TestGenerateBlockAndImportEthash(t *testing.T) {
  189. testGenerateBlockAndImport(t, false)
  190. }
  191. func TestGenerateBlockAndImportClique(t *testing.T) {
  192. testGenerateBlockAndImport(t, true)
  193. }
  194. func testGenerateBlockAndImport(t *testing.T, isClique bool) {
  195. var (
  196. engine consensus.Engine
  197. chainConfig *params.ChainConfig
  198. db = rawdb.NewMemoryDatabase()
  199. )
  200. if isClique {
  201. chainConfig = params.AllCliqueProtocolChanges
  202. chainConfig.Clique = &params.CliqueConfig{Period: 1, Epoch: 30000}
  203. engine = clique.New(chainConfig.Clique, db)
  204. } else {
  205. chainConfig = params.AllEthashProtocolChanges
  206. engine = ethash.NewFaker()
  207. }
  208. w, b := newTestWorker(t, chainConfig, engine, db, 0)
  209. defer w.close()
  210. // This test chain imports the mined blocks.
  211. db2 := rawdb.NewMemoryDatabase()
  212. b.genesis.MustCommit(db2)
  213. chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), engine, vm.Config{}, nil, nil, nil)
  214. defer chain.Stop()
  215. // Ignore empty commit here for less noise.
  216. w.skipSealHook = func(task *task) bool {
  217. return len(task.receipts) == 0
  218. }
  219. // Wait for mined blocks.
  220. sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
  221. defer sub.Unsubscribe()
  222. // Start mining!
  223. w.start()
  224. for i := 0; i < 5; i++ {
  225. b.txPool.AddLocal(b.newRandomTx(true, false))
  226. b.txPool.AddLocal(b.newRandomTx(false, false))
  227. w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
  228. w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
  229. select {
  230. case ev := <-sub.Chan():
  231. block := ev.Data.(core.NewMinedBlockEvent).Block
  232. if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
  233. t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err)
  234. }
  235. case <-time.After(3 * time.Second): // Worker needs 1s to include new changes.
  236. t.Fatalf("timeout")
  237. }
  238. }
  239. }
  240. func TestEmptyWorkEthash(t *testing.T) {
  241. testEmptyWork(t, ethashChainConfig, ethash.NewFaker())
  242. }
  243. func TestEmptyWorkClique(t *testing.T) {
  244. testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  245. }
  246. func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  247. defer engine.Close()
  248. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  249. defer w.close()
  250. var (
  251. taskIndex int
  252. taskCh = make(chan struct{}, 2)
  253. )
  254. checkEqual := func(t *testing.T, task *task, index int) {
  255. // The first empty work without any txs included
  256. receiptLen, balance := 0, big.NewInt(0)
  257. if index == 1 {
  258. // The second full work with 1 tx included
  259. receiptLen, balance = 1, big.NewInt(1000)
  260. }
  261. if len(task.receipts) != receiptLen {
  262. t.Fatalf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  263. }
  264. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  265. t.Fatalf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  266. }
  267. }
  268. w.newTaskHook = func(task *task) {
  269. if task.block.NumberU64() == 1 {
  270. checkEqual(t, task, taskIndex)
  271. taskIndex += 1
  272. taskCh <- struct{}{}
  273. }
  274. }
  275. w.skipSealHook = func(task *task) bool { return true }
  276. w.fullTaskHook = func() {
  277. time.Sleep(100 * time.Millisecond)
  278. }
  279. w.start() // Start mining!
  280. for i := 0; i < 2; i += 1 {
  281. select {
  282. case <-taskCh:
  283. case <-time.NewTimer(3 * time.Second).C:
  284. t.Error("new task timeout")
  285. }
  286. }
  287. }
  288. func TestStreamUncleBlock(t *testing.T) {
  289. ethash := ethash.NewFaker()
  290. defer ethash.Close()
  291. w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1)
  292. defer w.close()
  293. var taskCh = make(chan struct{})
  294. taskIndex := 0
  295. w.newTaskHook = func(task *task) {
  296. if task.block.NumberU64() == 2 {
  297. // The first task is an empty task, the second
  298. // one has 1 pending tx, the third one has 1 tx
  299. // and 1 uncle.
  300. if taskIndex == 2 {
  301. have := task.block.Header().UncleHash
  302. want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
  303. if have != want {
  304. t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex())
  305. }
  306. }
  307. taskCh <- struct{}{}
  308. taskIndex += 1
  309. }
  310. }
  311. w.skipSealHook = func(task *task) bool {
  312. return true
  313. }
  314. w.fullTaskHook = func() {
  315. time.Sleep(100 * time.Millisecond)
  316. }
  317. w.start()
  318. for i := 0; i < 2; i += 1 {
  319. select {
  320. case <-taskCh:
  321. case <-time.NewTimer(time.Second).C:
  322. t.Error("new task timeout")
  323. }
  324. }
  325. w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock})
  326. select {
  327. case <-taskCh:
  328. case <-time.NewTimer(time.Second).C:
  329. t.Error("new task timeout")
  330. }
  331. }
  332. func TestRegenerateMiningBlockEthash(t *testing.T) {
  333. testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
  334. }
  335. func TestRegenerateMiningBlockClique(t *testing.T) {
  336. testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  337. }
  338. func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  339. defer engine.Close()
  340. w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  341. defer w.close()
  342. var taskCh = make(chan struct{})
  343. taskIndex := 0
  344. w.newTaskHook = func(task *task) {
  345. if task.block.NumberU64() == 1 {
  346. // The first task is an empty task, the second
  347. // one has 1 pending tx, the third one has 2 txs
  348. if taskIndex == 2 {
  349. receiptLen, balance := 2, big.NewInt(2000)
  350. if len(task.receipts) != receiptLen {
  351. t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  352. }
  353. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  354. t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  355. }
  356. }
  357. taskCh <- struct{}{}
  358. taskIndex += 1
  359. }
  360. }
  361. w.skipSealHook = func(task *task) bool {
  362. return true
  363. }
  364. w.fullTaskHook = func() {
  365. time.Sleep(100 * time.Millisecond)
  366. }
  367. w.start()
  368. // Ignore the first two works
  369. for i := 0; i < 2; i += 1 {
  370. select {
  371. case <-taskCh:
  372. case <-time.NewTimer(time.Second).C:
  373. t.Error("new task timeout")
  374. }
  375. }
  376. b.txPool.AddLocals(newTxs)
  377. time.Sleep(time.Second)
  378. select {
  379. case <-taskCh:
  380. case <-time.NewTimer(time.Second).C:
  381. t.Error("new task timeout")
  382. }
  383. }
  384. func TestAdjustIntervalEthash(t *testing.T) {
  385. testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
  386. }
  387. func TestAdjustIntervalClique(t *testing.T) {
  388. testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  389. }
  390. func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  391. defer engine.Close()
  392. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  393. defer w.close()
  394. w.skipSealHook = func(task *task) bool {
  395. return true
  396. }
  397. w.fullTaskHook = func() {
  398. time.Sleep(100 * time.Millisecond)
  399. }
  400. var (
  401. progress = make(chan struct{}, 10)
  402. result = make([]float64, 0, 10)
  403. index = 0
  404. start uint32
  405. )
  406. w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
  407. // Short circuit if interval checking hasn't started.
  408. if atomic.LoadUint32(&start) == 0 {
  409. return
  410. }
  411. var wantMinInterval, wantRecommitInterval time.Duration
  412. switch index {
  413. case 0:
  414. wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
  415. case 1:
  416. origin := float64(3 * time.Second.Nanoseconds())
  417. estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
  418. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  419. case 2:
  420. estimate := result[index-1]
  421. min := float64(3 * time.Second.Nanoseconds())
  422. estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
  423. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  424. case 3:
  425. wantMinInterval, wantRecommitInterval = time.Second, time.Second
  426. }
  427. // Check interval
  428. if minInterval != wantMinInterval {
  429. t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
  430. }
  431. if recommitInterval != wantRecommitInterval {
  432. t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
  433. }
  434. result = append(result, float64(recommitInterval.Nanoseconds()))
  435. index += 1
  436. progress <- struct{}{}
  437. }
  438. w.start()
  439. time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt
  440. atomic.StoreUint32(&start, 1)
  441. w.setRecommitInterval(3 * time.Second)
  442. select {
  443. case <-progress:
  444. case <-time.NewTimer(time.Second).C:
  445. t.Error("interval reset timeout")
  446. }
  447. w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
  448. select {
  449. case <-progress:
  450. case <-time.NewTimer(time.Second).C:
  451. t.Error("interval reset timeout")
  452. }
  453. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  454. select {
  455. case <-progress:
  456. case <-time.NewTimer(time.Second).C:
  457. t.Error("interval reset timeout")
  458. }
  459. w.setRecommitInterval(500 * time.Millisecond)
  460. select {
  461. case <-progress:
  462. case <-time.NewTimer(time.Second).C:
  463. t.Error("interval reset timeout")
  464. }
  465. }
  466. var PSI1PSM = mps.PrivateStateMetadata{
  467. ID: "psi1",
  468. Name: "psi1",
  469. Description: "private state 1",
  470. Type: mps.Resident,
  471. Addresses: nil,
  472. }
  473. var PSI2PSM = mps.PrivateStateMetadata{
  474. ID: "psi2",
  475. Name: "psi2",
  476. Description: "private state 2",
  477. Type: mps.Resident,
  478. Addresses: nil,
  479. }
  480. func TestPrivatePSMRStateCreated(t *testing.T) {
  481. mockCtrl := gomock.NewController(t)
  482. defer mockCtrl.Finish()
  483. mockptm := private.NewMockPrivateTransactionManager(mockCtrl)
  484. mockptm.EXPECT().HasFeature(engine.MultiplePrivateStates).Return(true)
  485. mockptm.EXPECT().Groups().Return([]engine.PrivacyGroup{
  486. {
  487. Type: "RESIDENT",
  488. Name: PSI1PSM.Name,
  489. PrivacyGroupId: base64.StdEncoding.EncodeToString([]byte(PSI1PSM.ID)),
  490. Description: "Resident Group 1",
  491. From: "",
  492. Members: []string{"psi1"},
  493. },
  494. {
  495. Type: "RESIDENT",
  496. Name: PSI2PSM.Name,
  497. PrivacyGroupId: base64.StdEncoding.EncodeToString([]byte(PSI2PSM.ID)),
  498. Description: "Resident Group 2",
  499. From: "",
  500. Members: []string{"psi2"},
  501. },
  502. }, nil)
  503. saved := private.P
  504. defer func() {
  505. private.P = saved
  506. }()
  507. private.P = mockptm
  508. db := rawdb.NewMemoryDatabase()
  509. chainConfig := params.AllCliqueProtocolChanges
  510. chainConfig.IsQuorum = true
  511. chainConfig.IsMPS = true
  512. defer func() { chainConfig.IsQuorum = false }()
  513. defer func() { chainConfig.IsMPS = false }()
  514. w, b := newTestWorker(t, chainConfig, clique.New(chainConfig.Clique, db), db, 0)
  515. defer w.close()
  516. newBlock := make(chan *types.Block)
  517. listenNewBlock := func() {
  518. sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
  519. defer sub.Unsubscribe()
  520. for item := range sub.Chan() {
  521. newBlock <- item.Data.(core.NewMinedBlockEvent).Block
  522. }
  523. }
  524. w.start() // Start mining!
  525. // Ignore first 2 commits caused by start operation
  526. ignored := make(chan struct{}, 2)
  527. w.skipSealHook = func(task *task) bool {
  528. ignored <- struct{}{}
  529. return true
  530. }
  531. timer := time.NewTimer(3 * time.Second)
  532. for i := 0; i < 2; i++ {
  533. select {
  534. case <-ignored:
  535. case <-timer.C:
  536. t.Fatalf("timeout")
  537. }
  538. }
  539. timer.Stop()
  540. go listenNewBlock()
  541. // Ignore empty commit here for less noise
  542. w.skipSealHook = func(task *task) bool {
  543. return len(task.receipts) == 0
  544. }
  545. for i := 0; i < 5; i++ {
  546. randomPrivateTx := b.newRandomTx(true, true)
  547. mockptm.EXPECT().Receive(common.BytesToEncryptedPayloadHash(randomPrivateTx.Data())).Return("", []string{"psi1", "psi2"}, common.FromHex(testCode), nil, nil).AnyTimes()
  548. mockptm.EXPECT().Receive(common.EncryptedPayloadHash{}).Return("", []string{}, common.EncryptedPayloadHash{}.Bytes(), nil, nil).AnyTimes()
  549. expectedContractAddress := crypto.CreateAddress(randomPrivateTx.From(), randomPrivateTx.Nonce())
  550. b.txPool.AddLocal(randomPrivateTx)
  551. select {
  552. case blk := <-newBlock:
  553. //check if the tx is present
  554. found := blk.Transaction(randomPrivateTx.Hash())
  555. if found == nil {
  556. continue
  557. }
  558. latestBlockRoot := b.BlockChain().CurrentBlock().Root()
  559. _, privDb, err := b.BlockChain().StateAtPSI(latestBlockRoot, types.ToPrivateStateIdentifier("empty"))
  560. assert.NoError(t, err)
  561. assert.True(t, privDb.Exist(expectedContractAddress))
  562. assert.Equal(t, privDb.GetCodeSize(expectedContractAddress), 0)
  563. //contract should exist on both psi states and not be empty
  564. _, privDb, _ = b.BlockChain().StateAtPSI(latestBlockRoot, types.ToPrivateStateIdentifier("psi1"))
  565. assert.True(t, privDb.Exist(expectedContractAddress))
  566. assert.False(t, privDb.Empty(expectedContractAddress))
  567. assert.NotEqual(t, privDb.GetCodeSize(expectedContractAddress), 0)
  568. _, privDb, _ = b.BlockChain().StateAtPSI(latestBlockRoot, types.ToPrivateStateIdentifier("psi2"))
  569. assert.True(t, privDb.Exist(expectedContractAddress))
  570. assert.False(t, privDb.Empty(expectedContractAddress))
  571. assert.NotEqual(t, privDb.GetCodeSize(expectedContractAddress), 0)
  572. //contract should exist on random state (delegated to emptystate) but no contract code
  573. _, privDb, _ = b.BlockChain().StateAtPSI(latestBlockRoot, types.ToPrivateStateIdentifier("other"))
  574. assert.True(t, privDb.Exist(expectedContractAddress))
  575. assert.Equal(t, privDb.GetCodeSize(expectedContractAddress), 0)
  576. case <-time.NewTimer(3 * time.Second).C: // Worker needs 1s to include new changes.
  577. t.Fatalf("timeout")
  578. }
  579. }
  580. logsChan := make(chan []*types.Log)
  581. sub := b.BlockChain().SubscribeLogsEvent(logsChan)
  582. defer sub.Unsubscribe()
  583. logsContractData := "6080604052348015600f57600080fd5b507f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405160405180910390a1603e8060496000396000f3fe6080604052600080fdfea265627a7a72315820937805cb4f2481262ad95d420ab93220f11ceaea518c7ccf119fc2c58f58050d64736f6c63430005110032"
  584. tx, _ := types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), 470000, nil, common.FromHex(logsContractData)), types.QuorumPrivateTxSigner{}, testBankKey)
  585. mockptm.EXPECT().Receive(common.BytesToEncryptedPayloadHash(tx.Data())).Return("", []string{"psi1", "psi2"}, common.FromHex(logsContractData), nil, nil).AnyTimes()
  586. b.txPool.AddLocal(tx)
  587. select {
  588. case logs := <-logsChan:
  589. assert.Len(t, logs, 2)
  590. assert.Contains(t, []types.PrivateStateIdentifier{logs[0].PSI, logs[1].PSI}, types.PrivateStateIdentifier("psi1"))
  591. assert.Contains(t, []types.PrivateStateIdentifier{logs[0].PSI, logs[1].PSI}, types.PrivateStateIdentifier("psi2"))
  592. case <-time.NewTimer(3 * time.Second).C:
  593. t.Error("timeout")
  594. }
  595. }
  596. func TestPrivateLegacyStateCreated(t *testing.T) {
  597. mockCtrl := gomock.NewController(t)
  598. defer mockCtrl.Finish()
  599. mockptm := private.NewMockPrivateTransactionManager(mockCtrl)
  600. saved := private.P
  601. defer func() {
  602. private.P = saved
  603. }()
  604. private.P = mockptm
  605. db := rawdb.NewMemoryDatabase()
  606. chainConfig := params.AllCliqueProtocolChanges
  607. chainConfig.IsQuorum = true
  608. chainConfig.IsMPS = false
  609. defer func() { chainConfig.IsQuorum = false }()
  610. w, b := newTestWorker(t, chainConfig, clique.New(chainConfig.Clique, db), db, 0)
  611. defer w.close()
  612. newBlock := make(chan *types.Block)
  613. listenNewBlock := func() {
  614. sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
  615. defer sub.Unsubscribe()
  616. for item := range sub.Chan() {
  617. newBlock <- item.Data.(core.NewMinedBlockEvent).Block
  618. }
  619. }
  620. w.start() // Start mining!
  621. // Ignore first 2 commits caused by start operation
  622. ignored := make(chan struct{}, 2)
  623. w.skipSealHook = func(task *task) bool {
  624. ignored <- struct{}{}
  625. return true
  626. }
  627. for i := 0; i < 2; i++ {
  628. <-ignored
  629. }
  630. go listenNewBlock()
  631. // Ignore empty commit here for less noise
  632. w.skipSealHook = func(task *task) bool {
  633. return len(task.receipts) == 0
  634. }
  635. for i := 0; i < 5; i++ {
  636. mockptm.EXPECT().Receive(gomock.Any()).Return("", []string{}, common.FromHex(testCode), nil, nil).Times(1)
  637. randomPrivateTx := b.newRandomTx(true, true)
  638. expectedContractAddress := crypto.CreateAddress(randomPrivateTx.From(), randomPrivateTx.Nonce())
  639. b.txPool.AddLocal(randomPrivateTx)
  640. select {
  641. case blk := <-newBlock:
  642. //check if the tx is present
  643. found := blk.Transaction(randomPrivateTx.Hash())
  644. if found == nil {
  645. continue
  646. }
  647. latestBlockRoot := b.BlockChain().CurrentBlock().Root()
  648. //contract exists on default state
  649. _, privDb, _ := b.BlockChain().StateAtPSI(latestBlockRoot, types.DefaultPrivateStateIdentifier)
  650. assert.True(t, privDb.Exist(expectedContractAddress))
  651. assert.NotEqual(t, privDb.GetCodeSize(expectedContractAddress), 0)
  652. //only "private" state on legacy psm
  653. _, _, err := b.BlockChain().StateAtPSI(latestBlockRoot, types.ToPrivateStateIdentifier("other"))
  654. assert.Error(t, err, "Only the 'private' psi is supported by the default private state manager")
  655. case <-time.NewTimer(3 * time.Second).C: // Worker needs 1s to include new changes.
  656. t.Fatalf("timeout")
  657. }
  658. }
  659. }