helper_test.go 12 KB

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