helper_test.go 12 KB

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