helper_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // Copyright 2016 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. // This file contains some shares testing functionality, common to multiple
  17. // different files and modules being tested.
  18. package les
  19. import (
  20. "crypto/rand"
  21. "math/big"
  22. "sync"
  23. "testing"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/mclock"
  27. "github.com/ethereum/go-ethereum/consensus/ethash"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/eth"
  34. "github.com/ethereum/go-ethereum/ethdb"
  35. "github.com/ethereum/go-ethereum/event"
  36. "github.com/ethereum/go-ethereum/les/flowcontrol"
  37. "github.com/ethereum/go-ethereum/light"
  38. "github.com/ethereum/go-ethereum/p2p"
  39. "github.com/ethereum/go-ethereum/p2p/enode"
  40. "github.com/ethereum/go-ethereum/params"
  41. )
  42. var (
  43. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  44. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  45. testBankFunds = big.NewInt(1000000000000000000)
  46. acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  47. acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  48. acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey)
  49. acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey)
  50. testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056")
  51. testContractAddr common.Address
  52. testContractCodeDeployed = testContractCode[16:]
  53. testContractDeployed = uint64(2)
  54. testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029")
  55. testEventEmitterAddr common.Address
  56. testBufLimit = uint64(1000000)
  57. testBufRecharge = uint64(1000)
  58. )
  59. /*
  60. contract test {
  61. uint256[100] data;
  62. function Put(uint256 addr, uint256 value) {
  63. data[addr] = value;
  64. }
  65. function Get(uint256 addr) constant returns (uint256 value) {
  66. return data[addr];
  67. }
  68. }
  69. */
  70. func testChainGen(i int, block *core.BlockGen) {
  71. signer := types.HomesteadSigner{}
  72. switch i {
  73. case 0:
  74. // In block 1, the test bank sends account #1 some ether.
  75. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  76. block.AddTx(tx)
  77. case 1:
  78. // In block 2, the test bank sends some more ether to account #1.
  79. // acc1Addr passes it on to account #2.
  80. // acc1Addr creates a test contract.
  81. // acc1Addr creates a test event.
  82. nonce := block.TxNonce(acc1Addr)
  83. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  84. tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  85. tx3, _ := types.SignTx(types.NewContractCreation(nonce+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, acc1Key)
  86. testContractAddr = crypto.CreateAddress(acc1Addr, nonce+1)
  87. tx4, _ := types.SignTx(types.NewContractCreation(nonce+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, acc1Key)
  88. testEventEmitterAddr = crypto.CreateAddress(acc1Addr, nonce+2)
  89. block.AddTx(tx1)
  90. block.AddTx(tx2)
  91. block.AddTx(tx3)
  92. block.AddTx(tx4)
  93. case 2:
  94. // Block 3 is empty but was mined by account #2.
  95. block.SetCoinbase(acc2Addr)
  96. block.SetExtra([]byte("yeehaw"))
  97. data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
  98. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
  99. block.AddTx(tx)
  100. case 3:
  101. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  102. b2 := block.PrevBlock(1).Header()
  103. b2.Extra = []byte("foo")
  104. block.AddUncle(b2)
  105. b3 := block.PrevBlock(2).Header()
  106. b3.Extra = []byte("foo")
  107. block.AddUncle(b3)
  108. data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
  109. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
  110. block.AddTx(tx)
  111. }
  112. }
  113. // testIndexers creates a set of indexers with specified params for testing purpose.
  114. func testIndexers(db ethdb.Database, odr light.OdrBackend, iConfig *light.IndexerConfig) (*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer) {
  115. chtIndexer := light.NewChtIndexer(db, odr, iConfig.ChtSize, iConfig.ChtConfirms)
  116. bloomIndexer := eth.NewBloomIndexer(db, iConfig.BloomSize, iConfig.BloomConfirms)
  117. bloomTrieIndexer := light.NewBloomTrieIndexer(db, odr, iConfig.BloomSize, iConfig.BloomTrieSize)
  118. bloomIndexer.AddChildIndexer(bloomTrieIndexer)
  119. return chtIndexer, bloomIndexer, bloomTrieIndexer
  120. }
  121. // newTestProtocolManager creates a new protocol manager for testing purposes,
  122. // with the given number of blocks already known, potential notification
  123. // channels for different events and relative chain indexers array.
  124. func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen), odr *LesOdr, peers *peerSet, db ethdb.Database, ulcConfig *eth.ULCConfig, testCost uint64, clock mclock.Clock) (*ProtocolManager, error) {
  125. var (
  126. evmux = new(event.TypeMux)
  127. engine = ethash.NewFaker()
  128. gspec = core.Genesis{
  129. Config: params.TestChainConfig,
  130. Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
  131. }
  132. genesis = gspec.MustCommit(db)
  133. chain BlockChain
  134. pool txPool
  135. )
  136. if peers == nil {
  137. peers = newPeerSet()
  138. }
  139. if lightSync {
  140. chain, _ = light.NewLightChain(odr, gspec.Config, engine)
  141. } else {
  142. blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}, nil)
  143. gchain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator)
  144. if _, err := blockchain.InsertChain(gchain); err != nil {
  145. panic(err)
  146. }
  147. chain = blockchain
  148. pool = core.NewTxPool(core.DefaultTxPoolConfig, gspec.Config, blockchain)
  149. }
  150. indexConfig := light.TestServerIndexerConfig
  151. if lightSync {
  152. indexConfig = light.TestClientIndexerConfig
  153. }
  154. pm, err := NewProtocolManager(gspec.Config, indexConfig, lightSync, NetworkId, evmux, engine, peers, chain, pool, db, odr, nil, nil, make(chan struct{}), new(sync.WaitGroup), ulcConfig, func() bool { return true })
  155. if err != nil {
  156. return nil, err
  157. }
  158. if !lightSync {
  159. srv := &LesServer{lesCommons: lesCommons{protocolManager: pm}}
  160. pm.server = srv
  161. pm.servingQueue = newServingQueue(int64(time.Millisecond*10), 1, nil)
  162. pm.servingQueue.setThreads(4)
  163. srv.defParams = flowcontrol.ServerParams{
  164. BufLimit: testBufLimit,
  165. MinRecharge: testBufRecharge,
  166. }
  167. srv.testCost = testCost
  168. srv.fcManager = flowcontrol.NewClientManager(nil, clock)
  169. }
  170. pm.Start(1000)
  171. return pm, nil
  172. }
  173. // newTestProtocolManagerMust creates a new protocol manager for testing purposes,
  174. // with the given number of blocks already known, potential notification
  175. // channels for different events and relative chain indexers array. In case of an error, the constructor force-
  176. // fails the test.
  177. func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen), odr *LesOdr, peers *peerSet, db ethdb.Database, ulcConfig *eth.ULCConfig) *ProtocolManager {
  178. pm, err := newTestProtocolManager(lightSync, blocks, generator, odr, peers, db, ulcConfig, 0, &mclock.System{})
  179. if err != nil {
  180. t.Fatalf("Failed to create protocol manager: %v", err)
  181. }
  182. return pm
  183. }
  184. // testPeer is a simulated peer to allow testing direct network calls.
  185. type testPeer struct {
  186. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  187. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  188. *peer
  189. }
  190. // newTestPeer creates a new peer registered at the given protocol manager.
  191. func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool, testCost uint64) (*testPeer, <-chan error) {
  192. // Create a message pipe to communicate through
  193. app, net := p2p.MsgPipe()
  194. // Generate a random id and create the peer
  195. var id enode.ID
  196. rand.Read(id[:])
  197. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  198. // Start the peer on a new thread
  199. errc := make(chan error, 1)
  200. go func() {
  201. select {
  202. case pm.newPeerCh <- peer:
  203. errc <- pm.handle(peer)
  204. case <-pm.quitSync:
  205. errc <- p2p.DiscQuitting
  206. }
  207. }()
  208. tp := &testPeer{
  209. app: app,
  210. net: net,
  211. peer: peer,
  212. }
  213. // Execute any implicitly requested handshakes and return
  214. if shake {
  215. var (
  216. genesis = pm.blockchain.Genesis()
  217. head = pm.blockchain.CurrentHeader()
  218. td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
  219. )
  220. tp.handshake(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), testCost)
  221. }
  222. return tp, errc
  223. }
  224. func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) {
  225. // Create a message pipe to communicate through
  226. app, net := p2p.MsgPipe()
  227. // Generate a random id and create the peer
  228. var id enode.ID
  229. rand.Read(id[:])
  230. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  231. peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app)
  232. // Start the peer on a new thread
  233. errc := make(chan error, 1)
  234. errc2 := make(chan error, 1)
  235. go func() {
  236. select {
  237. case pm.newPeerCh <- peer:
  238. errc <- pm.handle(peer)
  239. case <-pm.quitSync:
  240. errc <- p2p.DiscQuitting
  241. }
  242. }()
  243. go func() {
  244. select {
  245. case pm2.newPeerCh <- peer2:
  246. errc2 <- pm2.handle(peer2)
  247. case <-pm2.quitSync:
  248. errc2 <- p2p.DiscQuitting
  249. }
  250. }()
  251. return peer, errc, peer2, errc2
  252. }
  253. // handshake simulates a trivial handshake that expects the same state from the
  254. // remote side as we are simulating locally.
  255. func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, testCost uint64) {
  256. var expList keyValueList
  257. expList = expList.add("protocolVersion", uint64(p.version))
  258. expList = expList.add("networkId", uint64(NetworkId))
  259. expList = expList.add("headTd", td)
  260. expList = expList.add("headHash", head)
  261. expList = expList.add("headNum", headNum)
  262. expList = expList.add("genesisHash", genesis)
  263. sendList := make(keyValueList, len(expList))
  264. copy(sendList, expList)
  265. expList = expList.add("serveHeaders", nil)
  266. expList = expList.add("serveChainSince", uint64(0))
  267. expList = expList.add("serveStateSince", uint64(0))
  268. expList = expList.add("serveRecentState", uint64(core.TriesInMemory-4))
  269. expList = expList.add("txRelay", nil)
  270. expList = expList.add("flowControl/BL", testBufLimit)
  271. expList = expList.add("flowControl/MRR", testBufRecharge)
  272. expList = expList.add("flowControl/MRC", testCostList(testCost))
  273. if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil {
  274. t.Fatalf("status recv: %v", err)
  275. }
  276. if err := p2p.Send(p.app, StatusMsg, sendList); err != nil {
  277. t.Fatalf("status send: %v", err)
  278. }
  279. p.fcParams = flowcontrol.ServerParams{
  280. BufLimit: testBufLimit,
  281. MinRecharge: testBufRecharge,
  282. }
  283. }
  284. // close terminates the local side of the peer, notifying the remote protocol
  285. // manager of termination.
  286. func (p *testPeer) close() {
  287. p.app.Close()
  288. }
  289. // TestEntity represents a network entity for testing with necessary auxiliary fields.
  290. type TestEntity struct {
  291. db ethdb.Database
  292. rPeer *peer
  293. tPeer *testPeer
  294. peers *peerSet
  295. pm *ProtocolManager
  296. // Indexers
  297. chtIndexer *core.ChainIndexer
  298. bloomIndexer *core.ChainIndexer
  299. bloomTrieIndexer *core.ChainIndexer
  300. }
  301. // newServerEnv creates a server testing environment with a connected test peer for testing purpose.
  302. func newServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer)) (*TestEntity, func()) {
  303. db := rawdb.NewMemoryDatabase()
  304. cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig)
  305. pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, nil, db, nil)
  306. peer, _ := newTestPeer(t, "peer", protocol, pm, true, 0)
  307. cIndexer.Start(pm.blockchain.(*core.BlockChain))
  308. bIndexer.Start(pm.blockchain.(*core.BlockChain))
  309. // Wait until indexers generate enough index data.
  310. if waitIndexers != nil {
  311. waitIndexers(cIndexer, bIndexer, btIndexer)
  312. }
  313. return &TestEntity{
  314. db: db,
  315. tPeer: peer,
  316. pm: pm,
  317. chtIndexer: cIndexer,
  318. bloomIndexer: bIndexer,
  319. bloomTrieIndexer: btIndexer,
  320. }, func() {
  321. peer.close()
  322. // Note bloom trie indexer will be closed by it parent recursively.
  323. cIndexer.Close()
  324. bIndexer.Close()
  325. }
  326. }
  327. // newClientServerEnv creates a client/server arch environment with a connected les server and light client pair
  328. // for testing purpose.
  329. func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer), newPeer bool) (*TestEntity, *TestEntity, func()) {
  330. db, ldb := rawdb.NewMemoryDatabase(), rawdb.NewMemoryDatabase()
  331. peers, lPeers := newPeerSet(), newPeerSet()
  332. dist := newRequestDistributor(lPeers, make(chan struct{}), &mclock.System{})
  333. rm := newRetrieveManager(lPeers, dist, nil)
  334. odr := NewLesOdr(ldb, light.TestClientIndexerConfig, rm)
  335. cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig)
  336. lcIndexer, lbIndexer, lbtIndexer := testIndexers(ldb, odr, light.TestClientIndexerConfig)
  337. odr.SetIndexers(lcIndexer, lbtIndexer, lbIndexer)
  338. pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, peers, db, nil)
  339. lpm := newTestProtocolManagerMust(t, true, 0, nil, odr, lPeers, ldb, nil)
  340. startIndexers := func(clientMode bool, pm *ProtocolManager) {
  341. if clientMode {
  342. lcIndexer.Start(pm.blockchain.(*light.LightChain))
  343. lbIndexer.Start(pm.blockchain.(*light.LightChain))
  344. } else {
  345. cIndexer.Start(pm.blockchain.(*core.BlockChain))
  346. bIndexer.Start(pm.blockchain.(*core.BlockChain))
  347. }
  348. }
  349. startIndexers(false, pm)
  350. startIndexers(true, lpm)
  351. // Execute wait until function if it is specified.
  352. if waitIndexers != nil {
  353. waitIndexers(cIndexer, bIndexer, btIndexer)
  354. }
  355. var (
  356. peer, lPeer *peer
  357. err1, err2 <-chan error
  358. )
  359. if newPeer {
  360. peer, err1, lPeer, err2 = newTestPeerPair("peer", protocol, pm, lpm)
  361. select {
  362. case <-time.After(time.Millisecond * 100):
  363. case err := <-err1:
  364. t.Fatalf("peer 1 handshake error: %v", err)
  365. case err := <-err2:
  366. t.Fatalf("peer 2 handshake error: %v", err)
  367. }
  368. }
  369. return &TestEntity{
  370. db: db,
  371. pm: pm,
  372. rPeer: peer,
  373. peers: peers,
  374. chtIndexer: cIndexer,
  375. bloomIndexer: bIndexer,
  376. bloomTrieIndexer: btIndexer,
  377. }, &TestEntity{
  378. db: ldb,
  379. pm: lpm,
  380. rPeer: lPeer,
  381. peers: lPeers,
  382. chtIndexer: lcIndexer,
  383. bloomIndexer: lbIndexer,
  384. bloomTrieIndexer: lbtIndexer,
  385. }, func() {
  386. // Note bloom trie indexers will be closed by their parents recursively.
  387. cIndexer.Close()
  388. bIndexer.Close()
  389. lcIndexer.Close()
  390. lbIndexer.Close()
  391. }
  392. }