helper_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus/ethash"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/core/vm"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/eth"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/event"
  33. "github.com/ethereum/go-ethereum/les/flowcontrol"
  34. "github.com/ethereum/go-ethereum/light"
  35. "github.com/ethereum/go-ethereum/p2p"
  36. "github.com/ethereum/go-ethereum/p2p/discover"
  37. "github.com/ethereum/go-ethereum/params"
  38. )
  39. var (
  40. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  41. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  42. testBankFunds = big.NewInt(1000000000000000000)
  43. acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  44. acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  45. acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey)
  46. acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey)
  47. testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056")
  48. testContractAddr common.Address
  49. testContractCodeDeployed = testContractCode[16:]
  50. testContractDeployed = uint64(2)
  51. testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029")
  52. testEventEmitterAddr common.Address
  53. testBufLimit = uint64(100)
  54. )
  55. /*
  56. contract test {
  57. uint256[100] data;
  58. function Put(uint256 addr, uint256 value) {
  59. data[addr] = value;
  60. }
  61. function Get(uint256 addr) constant returns (uint256 value) {
  62. return data[addr];
  63. }
  64. }
  65. */
  66. func testChainGen(i int, block *core.BlockGen) {
  67. signer := types.HomesteadSigner{}
  68. switch i {
  69. case 0:
  70. // In block 1, the test bank sends account #1 some ether.
  71. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  72. block.AddTx(tx)
  73. case 1:
  74. // In block 2, the test bank sends some more ether to account #1.
  75. // acc1Addr passes it on to account #2.
  76. // acc1Addr creates a test contract.
  77. // acc1Addr creates a test event.
  78. nonce := block.TxNonce(acc1Addr)
  79. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  80. tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  81. tx3, _ := types.SignTx(types.NewContractCreation(nonce+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, acc1Key)
  82. testContractAddr = crypto.CreateAddress(acc1Addr, nonce+1)
  83. tx4, _ := types.SignTx(types.NewContractCreation(nonce+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, acc1Key)
  84. testEventEmitterAddr = crypto.CreateAddress(acc1Addr, nonce+2)
  85. block.AddTx(tx1)
  86. block.AddTx(tx2)
  87. block.AddTx(tx3)
  88. block.AddTx(tx4)
  89. case 2:
  90. // Block 3 is empty but was mined by account #2.
  91. block.SetCoinbase(acc2Addr)
  92. block.SetExtra([]byte("yeehaw"))
  93. data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
  94. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
  95. block.AddTx(tx)
  96. case 3:
  97. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  98. b2 := block.PrevBlock(1).Header()
  99. b2.Extra = []byte("foo")
  100. block.AddUncle(b2)
  101. b3 := block.PrevBlock(2).Header()
  102. b3.Extra = []byte("foo")
  103. block.AddUncle(b3)
  104. data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
  105. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
  106. block.AddTx(tx)
  107. }
  108. }
  109. func testRCL() RequestCostList {
  110. cl := make(RequestCostList, len(reqList))
  111. for i, code := range reqList {
  112. cl[i].MsgCode = code
  113. cl[i].BaseCost = 0
  114. cl[i].ReqCost = 0
  115. }
  116. return cl
  117. }
  118. // newTestProtocolManager creates a new protocol manager for testing purposes,
  119. // with the given number of blocks already known, and potential notification
  120. // channels for different events.
  121. func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen), peers *peerSet, odr *LesOdr, db ethdb.Database) (*ProtocolManager, error) {
  122. var (
  123. evmux = new(event.TypeMux)
  124. engine = ethash.NewFaker()
  125. gspec = core.Genesis{
  126. Config: params.TestChainConfig,
  127. Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
  128. }
  129. genesis = gspec.MustCommit(db)
  130. chain BlockChain
  131. )
  132. if peers == nil {
  133. peers = newPeerSet()
  134. }
  135. if lightSync {
  136. chain, _ = light.NewLightChain(odr, gspec.Config, engine)
  137. } else {
  138. blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{})
  139. chtIndexer := light.NewChtIndexer(db, false)
  140. chtIndexer.Start(blockchain)
  141. bbtIndexer := light.NewBloomTrieIndexer(db, false)
  142. bloomIndexer := eth.NewBloomIndexer(db, params.BloomBitsBlocks)
  143. bloomIndexer.AddChildIndexer(bbtIndexer)
  144. bloomIndexer.Start(blockchain)
  145. gchain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator)
  146. if _, err := blockchain.InsertChain(gchain); err != nil {
  147. panic(err)
  148. }
  149. chain = blockchain
  150. }
  151. var protocolVersions []uint
  152. if lightSync {
  153. protocolVersions = ClientProtocolVersions
  154. } else {
  155. protocolVersions = ServerProtocolVersions
  156. }
  157. pm, err := NewProtocolManager(gspec.Config, lightSync, protocolVersions, NetworkId, evmux, engine, peers, chain, nil, db, odr, nil, make(chan struct{}), new(sync.WaitGroup))
  158. if err != nil {
  159. return nil, err
  160. }
  161. if !lightSync {
  162. srv := &LesServer{protocolManager: pm}
  163. pm.server = srv
  164. srv.defParams = &flowcontrol.ServerParams{
  165. BufLimit: testBufLimit,
  166. MinRecharge: 1,
  167. }
  168. srv.fcManager = flowcontrol.NewClientManager(50, 10, 1000000000)
  169. srv.fcCostStats = newCostStats(nil)
  170. }
  171. pm.Start(1000)
  172. return pm, nil
  173. }
  174. // newTestProtocolManagerMust creates a new protocol manager for testing purposes,
  175. // with the given number of blocks already known, and potential notification
  176. // channels for different events. In case of an error, the constructor force-
  177. // fails the test.
  178. func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen), peers *peerSet, odr *LesOdr, db ethdb.Database) *ProtocolManager {
  179. pm, err := newTestProtocolManager(lightSync, blocks, generator, peers, odr, db)
  180. if err != nil {
  181. t.Fatalf("Failed to create protocol manager: %v", err)
  182. }
  183. return pm
  184. }
  185. // testPeer is a simulated peer to allow testing direct network calls.
  186. type testPeer struct {
  187. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  188. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  189. *peer
  190. }
  191. // newTestPeer creates a new peer registered at the given protocol manager.
  192. func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
  193. // Create a message pipe to communicate through
  194. app, net := p2p.MsgPipe()
  195. // Generate a random id and create the peer
  196. var id discover.NodeID
  197. rand.Read(id[:])
  198. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  199. // Start the peer on a new thread
  200. errc := make(chan error, 1)
  201. go func() {
  202. select {
  203. case pm.newPeerCh <- peer:
  204. errc <- pm.handle(peer)
  205. case <-pm.quitSync:
  206. errc <- p2p.DiscQuitting
  207. }
  208. }()
  209. tp := &testPeer{
  210. app: app,
  211. net: net,
  212. peer: peer,
  213. }
  214. // Execute any implicitly requested handshakes and return
  215. if shake {
  216. var (
  217. genesis = pm.blockchain.Genesis()
  218. head = pm.blockchain.CurrentHeader()
  219. td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
  220. )
  221. tp.handshake(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash())
  222. }
  223. return tp, errc
  224. }
  225. func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) {
  226. // Create a message pipe to communicate through
  227. app, net := p2p.MsgPipe()
  228. // Generate a random id and create the peer
  229. var id discover.NodeID
  230. rand.Read(id[:])
  231. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  232. peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app)
  233. // Start the peer on a new thread
  234. errc := make(chan error, 1)
  235. errc2 := make(chan error, 1)
  236. go func() {
  237. select {
  238. case pm.newPeerCh <- peer:
  239. errc <- pm.handle(peer)
  240. case <-pm.quitSync:
  241. errc <- p2p.DiscQuitting
  242. }
  243. }()
  244. go func() {
  245. select {
  246. case pm2.newPeerCh <- peer2:
  247. errc2 <- pm2.handle(peer2)
  248. case <-pm2.quitSync:
  249. errc2 <- p2p.DiscQuitting
  250. }
  251. }()
  252. return peer, errc, peer2, errc2
  253. }
  254. // handshake simulates a trivial handshake that expects the same state from the
  255. // remote side as we are simulating locally.
  256. func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) {
  257. var expList keyValueList
  258. expList = expList.add("protocolVersion", uint64(p.version))
  259. expList = expList.add("networkId", uint64(NetworkId))
  260. expList = expList.add("headTd", td)
  261. expList = expList.add("headHash", head)
  262. expList = expList.add("headNum", headNum)
  263. expList = expList.add("genesisHash", genesis)
  264. sendList := make(keyValueList, len(expList))
  265. copy(sendList, expList)
  266. expList = expList.add("serveHeaders", nil)
  267. expList = expList.add("serveChainSince", uint64(0))
  268. expList = expList.add("serveStateSince", uint64(0))
  269. expList = expList.add("txRelay", nil)
  270. expList = expList.add("flowControl/BL", testBufLimit)
  271. expList = expList.add("flowControl/MRR", uint64(1))
  272. expList = expList.add("flowControl/MRC", testRCL())
  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.fcServerParams = &flowcontrol.ServerParams{
  280. BufLimit: testBufLimit,
  281. MinRecharge: 1,
  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. }