func TestPeerSend(t *testing.T) { // Start a tester and execute the handshake tester, err := startTestPeerInited() if err != nil { t.Fatalf("failed to start initialized peer: %v", err) } defer tester.stream.Close() // Construct a message and inject into the tester message := NewMessage([]byte("peer broadcast test message")) envelope, err := message.Wrap(DefaultPoW, Options{ TTL: DefaultTTL, }) if err != nil { t.Fatalf("failed to wrap message: %v", err) } if err := tester.client.Send(envelope); err != nil { t.Fatalf("failed to send message: %v", err) } // Check that the message is eventually forwarded payload := []interface{}{envelope} if err := p2p.ExpectMsg(tester.stream, messagesCode, payload); err != nil { t.Fatalf("message mismatch: %v", err) } // Make sure that even with a re-insert, an empty batch is received if err := tester.client.Send(envelope); err != nil { t.Fatalf("failed to send message: %v", err) } if err := p2p.ExpectMsg(tester.stream, messagesCode, []interface{}{}); err != nil { t.Fatalf("message mismatch: %v", err) } }
func TestPeerMessageExpiration(t *testing.T) { // Start a tester and execute the handshake tester, err := startTestPeerInited() if err != nil { t.Fatalf("failed to start initialized peer: %v", err) } defer tester.stream.Close() // Fetch the peer instance for later inspection tester.client.peerMu.RLock() if peers := len(tester.client.peers); peers != 1 { t.Fatalf("peer pool size mismatch: have %v, want %v", peers, 1) } var peer *peer for peer, _ = range tester.client.peers { break } tester.client.peerMu.RUnlock() // Construct a message and pass it through the tester message := NewMessage([]byte("peer test message")) envelope, err := message.Wrap(DefaultPoW, Options{ TTL: time.Second, }) if err != nil { t.Fatalf("failed to wrap message: %v", err) } if err := tester.client.Send(envelope); err != nil { t.Fatalf("failed to send message: %v", err) } payload := []interface{}{envelope} if err := p2p.ExpectMsg(tester.stream, messagesCode, payload); err != nil { // A premature empty message may have been broadcast, check the next too if err := p2p.ExpectMsg(tester.stream, messagesCode, payload); err != nil { t.Fatalf("message mismatch: %v", err) } } // Check that the message is inside the cache if !peer.known.Has(envelope.Hash()) { t.Fatalf("message not found in cache") } // Discard messages until expiration and check cache again exp := time.Now().Add(time.Second + 2*expirationCycle + 100*time.Millisecond) for time.Now().Before(exp) { if err := p2p.ExpectMsg(tester.stream, messagesCode, []interface{}{}); err != nil { t.Fatalf("message mismatch: %v", err) } } if peer.known.Has(envelope.Hash()) { t.Fatalf("message not expired from cache") } }
func TestPeerHandshakeSuccess(t *testing.T) { tester := startTestPeer() // Wait for and check the handshake if err := p2p.ExpectMsg(tester.stream, statusCode, []uint64{protocolVersion}); err != nil { t.Fatalf("status message mismatch: %v", err) } // Send a valid handshake status and make sure connection stays live if err := p2p.SendItems(tester.stream, statusCode, protocolVersion); err != nil { t.Fatalf("failed to send status: %v", err) } select { case <-tester.termed: t.Fatalf("valid handshake disconnected") case <-time.After(100 * time.Millisecond): } // Clean up the test tester.stream.Close() select { case <-tester.termed: case <-time.After(time.Second): t.Fatalf("local close timed out") } }
func testGetReceipt(t *testing.T, protocol int) { // Define three accounts to simulate transactions with acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey) acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey) // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_makerts_test) generator := func(i int, block *core.BlockGen) { switch i { case 0: // In block 1, the test bank sends account #1 some ether. tx, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(testBankKey) block.AddTx(tx) case 1: // In block 2, the test bank sends some more ether to account #1. // acc1Addr passes it on to account #2. tx1, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey) tx2, _ := types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key) block.AddTx(tx1) block.AddTx(tx2) case 2: // Block 3 is empty but was mined by account #2. block.SetCoinbase(acc2Addr) block.SetExtra([]byte("yeehaw")) case 3: // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data). b2 := block.PrevBlock(1).Header() b2.Extra = []byte("foo") block.AddUncle(b2) b3 := block.PrevBlock(2).Header() b3.Extra = []byte("foo") block.AddUncle(b3) } } // Assemble the test environment pm := newTestProtocolManagerMust(t, false, 4, generator, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() // Collect the hashes to request, and the response to expect hashes, receipts := []common.Hash{}, []types.Receipts{} for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ { block := pm.blockchain.GetBlockByNumber(i) hashes = append(hashes, block.Hash()) receipts = append(receipts, core.GetBlockReceipts(pm.chaindb, block.Hash())) } // Send the hash request and verify the response p2p.Send(peer.app, 0x0f, hashes) if err := p2p.ExpectMsg(peer.app, 0x10, receipts); err != nil { t.Errorf("receipts mismatch: %v", err) } }
func startTestPeerInited() (*testPeer, error) { peer := startTestPeer() if err := p2p.ExpectMsg(peer.stream, statusCode, []uint64{protocolVersion}); err != nil { peer.stream.Close() return nil, err } if err := p2p.SendItems(peer.stream, statusCode, protocolVersion); err != nil { peer.stream.Close() return nil, err } return peer, nil }
// handshake simulates a trivial handshake that expects the same state from the // remote side as we are simulating locally. func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) { msg := &statusData{ ProtocolVersion: uint32(p.version), NetworkId: uint32(NetworkId), TD: td, CurrentBlock: head, GenesisBlock: genesis, } if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil { t.Fatalf("status recv: %v", err) } if err := p2p.Send(p.app, StatusMsg, msg); err != nil { t.Fatalf("status send: %v", err) } }
func (p *testPeer) handshake(t *testing.T) { td, currentBlock, genesis := p.pm.chainman.Status() msg := &statusData{ ProtocolVersion: uint32(p.pm.protVer), NetworkId: uint32(p.pm.netId), TD: td, CurrentBlock: currentBlock, GenesisBlock: genesis, } if err := p2p.ExpectMsg(p, StatusMsg, msg); err != nil { t.Fatalf("status recv: %v", err) } if err := p2p.Send(p, StatusMsg, msg); err != nil { t.Fatalf("status send: %v", err) } }
func TestPeerStatusMessage(t *testing.T) { tester := startTestPeer() // Wait for the handshake status message and check it if err := p2p.ExpectMsg(tester.stream, statusCode, []uint64{protocolVersion}); err != nil { t.Fatalf("status message mismatch: %v", err) } // Terminate the node tester.stream.Close() select { case <-tester.termed: case <-time.After(time.Second): t.Fatalf("local close timed out") } }
func TestPeerHandshakeFail(t *testing.T) { tester := startTestPeer() // Wait for and check the handshake if err := p2p.ExpectMsg(tester.stream, statusCode, []uint64{protocolVersion}); err != nil { t.Fatalf("status message mismatch: %v", err) } // Send an invalid handshake status and verify disconnect if err := p2p.SendItems(tester.stream, messagesCode); err != nil { t.Fatalf("failed to send malformed status: %v", err) } select { case <-tester.termed: case <-time.After(time.Second): t.Fatalf("remote close timed out") } }
func testGetBlockHashes(t *testing.T, protocol int) { pm := newTestProtocolManagerMust(t, false, downloader.MaxHashFetch+15, nil, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() // Create a batch of tests for various scenarios limit := downloader.MaxHashFetch tests := []struct { origin common.Hash number int result int }{ {common.Hash{}, 1, 0}, // Make sure non existent hashes don't return results {pm.blockchain.Genesis().Hash(), 1, 0}, // There are no hashes to retrieve up from the genesis {pm.blockchain.GetBlockByNumber(5).Hash(), 5, 5}, // All the hashes including the genesis requested {pm.blockchain.GetBlockByNumber(5).Hash(), 10, 5}, // More hashes than available till the genesis requested {pm.blockchain.GetBlockByNumber(100).Hash(), 10, 10}, // All hashes available from the middle of the chain {pm.blockchain.CurrentBlock().Hash(), 10, 10}, // All hashes available from the head of the chain {pm.blockchain.CurrentBlock().Hash(), limit, limit}, // Request the maximum allowed hash count {pm.blockchain.CurrentBlock().Hash(), limit + 1, limit}, // Request more than the maximum allowed hash count } // Run each of the tests and verify the results against the chain for i, tt := range tests { // Assemble the hash response we would like to receive resp := make([]common.Hash, tt.result) if len(resp) > 0 { from := pm.blockchain.GetBlock(tt.origin).NumberU64() - 1 for j := 0; j < len(resp); j++ { resp[j] = pm.blockchain.GetBlockByNumber(uint64(int(from) - j)).Hash() } } // Send the hash request and verify the response p2p.Send(peer.app, 0x03, getBlockHashesData{tt.origin, uint64(tt.number)}) if err := p2p.ExpectMsg(peer.app, 0x04, resp); err != nil { t.Errorf("test %d: block hashes mismatch: %v", i, err) } } }
func testGetBlockHashesFromNumber(t *testing.T, protocol int) { pm := newTestProtocolManagerMust(t, false, downloader.MaxHashFetch+15, nil, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() // Create a batch of tests for various scenarios limit := downloader.MaxHashFetch tests := []struct { origin uint64 number int result int }{ {pm.blockchain.CurrentBlock().NumberU64() + 1, 1, 0}, // Out of bounds requests should return empty {pm.blockchain.CurrentBlock().NumberU64(), 1, 1}, // Make sure the head hash can be retrieved {pm.blockchain.CurrentBlock().NumberU64() - 4, 5, 5}, // All hashes, including the head hash requested {pm.blockchain.CurrentBlock().NumberU64() - 4, 10, 5}, // More hashes requested than available till the head {pm.blockchain.CurrentBlock().NumberU64() - 100, 10, 10}, // All hashes available from the middle of the chain {0, 10, 10}, // All hashes available from the root of the chain {0, limit, limit}, // Request the maximum allowed hash count {0, limit + 1, limit}, // Request more than the maximum allowed hash count {0, 1, 1}, // Make sure the genesis hash can be retrieved } // Run each of the tests and verify the results against the chain for i, tt := range tests { // Assemble the hash response we would like to receive resp := make([]common.Hash, tt.result) for j := 0; j < len(resp); j++ { resp[j] = pm.blockchain.GetBlockByNumber(tt.origin + uint64(j)).Hash() } // Send the hash request and verify the response p2p.Send(peer.app, 0x08, getBlockHashesFromNumberData{tt.origin, uint64(tt.number)}) if err := p2p.ExpectMsg(peer.app, 0x04, resp); err != nil { t.Errorf("test %d: block hashes mismatch: %v", i, err) } } }
func testGetBlockBodies(t *testing.T, protocol int) { pm := newTestProtocolManagerMust(t, false, downloader.MaxBlockFetch+15, nil, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() // Create a batch of tests for various scenarios limit := downloader.MaxBlockFetch tests := []struct { random int // Number of blocks to fetch randomly from the chain explicit []common.Hash // Explicitly requested blocks available []bool // Availability of explicitly requested blocks expected int // Total number of existing blocks to expect }{ {1, nil, nil, 1}, // A single random block should be retrievable {10, nil, nil, 10}, // Multiple random blocks should be retrievable {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable {0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned // Existing and non-existing blocks interleaved should not cause problems {0, []common.Hash{ common.Hash{}, pm.blockchain.GetBlockByNumber(1).Hash(), common.Hash{}, pm.blockchain.GetBlockByNumber(10).Hash(), common.Hash{}, pm.blockchain.GetBlockByNumber(100).Hash(), common.Hash{}, }, []bool{false, true, false, true, false, true, false}, 3}, } // Run each of the tests and verify the results against the chain for i, tt := range tests { // Collect the hashes to request, and the response to expect hashes, seen := []common.Hash{}, make(map[int64]bool) bodies := []*blockBody{} for j := 0; j < tt.random; j++ { for { num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64())) if !seen[num] { seen[num] = true block := pm.blockchain.GetBlockByNumber(uint64(num)) hashes = append(hashes, block.Hash()) if len(bodies) < tt.expected { bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()}) } break } } } for j, hash := range tt.explicit { hashes = append(hashes, hash) if tt.available[j] && len(bodies) < tt.expected { block := pm.blockchain.GetBlock(hash) bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()}) } } // Send the hash request and verify the response p2p.Send(peer.app, 0x05, hashes) if err := p2p.ExpectMsg(peer.app, 0x06, bodies); err != nil { t.Errorf("test %d: bodies mismatch: %v", i, err) } } }
func testGetBlockHeaders(t *testing.T, protocol int) { pm := newTestProtocolManagerMust(t, false, downloader.MaxHashFetch+15, nil, nil) peer, _ := newTestPeer("peer", protocol, pm, true) defer peer.close() // Create a "random" unknown hash for testing var unknown common.Hash for i, _ := range unknown { unknown[i] = byte(i) } // Create a batch of tests for various scenarios limit := uint64(downloader.MaxHeaderFetch) tests := []struct { query *getBlockHeadersData // The query to execute for header retrieval expect []common.Hash // The hashes of the block whose headers are expected }{ // A single random block should be retrievable by hash and number too { &getBlockHeadersData{Origin: hashOrNumber{Hash: pm.blockchain.GetBlockByNumber(limit / 2).Hash()}, Amount: 1}, []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()}, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1}, []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()}, }, // Multiple headers should be retrievable in both directions { &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3}, []common.Hash{ pm.blockchain.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 1).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 2).Hash(), }, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true}, []common.Hash{ pm.blockchain.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 1).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 2).Hash(), }, }, // Multiple headers with skip lists should be retrievable { &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3}, []common.Hash{ pm.blockchain.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 4).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 8).Hash(), }, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true}, []common.Hash{ pm.blockchain.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 4).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 8).Hash(), }, }, // The chain endpoints should be retrievable { &getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1}, []common.Hash{pm.blockchain.GetBlockByNumber(0).Hash()}, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64()}, Amount: 1}, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, }, // Ensure protocol limits are honored { &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true}, pm.blockchain.GetBlockHashesFromHash(pm.blockchain.CurrentBlock().Hash(), limit), }, // Check that requesting more than available is handled gracefully { &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3}, []common.Hash{ pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(), pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64()).Hash(), }, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true}, []common.Hash{ pm.blockchain.GetBlockByNumber(4).Hash(), pm.blockchain.GetBlockByNumber(0).Hash(), }, }, // Check that requesting more than available is handled gracefully, even if mid skip { &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3}, []common.Hash{ pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(), pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 1).Hash(), }, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true}, []common.Hash{ pm.blockchain.GetBlockByNumber(4).Hash(), pm.blockchain.GetBlockByNumber(1).Hash(), }, }, // Check that non existing headers aren't returned { &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1}, []common.Hash{}, }, { &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() + 1}, Amount: 1}, []common.Hash{}, }, } // Run each of the tests and verify the results against the chain for i, tt := range tests { // Collect the headers to expect in the response headers := []*types.Header{} for _, hash := range tt.expect { headers = append(headers, pm.blockchain.GetBlock(hash).Header()) } // Send the hash request and verify the response p2p.Send(peer.app, 0x03, tt.query) if err := p2p.ExpectMsg(peer.app, 0x04, headers); err != nil { t.Errorf("test %d: headers mismatch: %v", i, err) } } }
func testDAOChallenge(t *testing.T, localForked, remoteForked bool, timeout bool) { // Reduce the DAO handshake challenge timeout if timeout { defer func(old time.Duration) { daoChallengeTimeout = old }(daoChallengeTimeout) daoChallengeTimeout = 500 * time.Millisecond } // Create a DAO aware protocol manager var ( evmux = new(event.TypeMux) pow = new(core.FakePow) db, _ = ethdb.NewMemDatabase() genesis = core.WriteGenesisBlockForTesting(db) config = &core.ChainConfig{DAOForkBlock: big.NewInt(1), DAOForkSupport: localForked} blockchain, _ = core.NewBlockChain(db, config, pow, evmux) ) pm, err := NewProtocolManager(config, false, NetworkId, evmux, new(testTxPool), pow, blockchain, db) if err != nil { t.Fatalf("failed to start test protocol manager: %v", err) } pm.Start() defer pm.Stop() // Connect a new peer and check that we receive the DAO challenge peer, _ := newTestPeer("peer", eth63, pm, true) defer peer.close() challenge := &getBlockHeadersData{ Origin: hashOrNumber{Number: config.DAOForkBlock.Uint64()}, Amount: 1, Skip: 0, Reverse: false, } if err := p2p.ExpectMsg(peer.app, GetBlockHeadersMsg, challenge); err != nil { t.Fatalf("challenge mismatch: %v", err) } // Create a block to reply to the challenge if no timeout is simualted if !timeout { blocks, _ := core.GenerateChain(nil, genesis, db, 1, func(i int, block *core.BlockGen) { if remoteForked { block.SetExtra(params.DAOForkBlockExtra) } }) if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{blocks[0].Header()}); err != nil { t.Fatalf("failed to answer challenge: %v", err) } time.Sleep(100 * time.Millisecond) // Sleep to avoid the verification racing with the drops } else { // Otherwise wait until the test timeout passes time.Sleep(daoChallengeTimeout + 500*time.Millisecond) } // Verify that depending on fork side, the remote peer is maintained or dropped if localForked == remoteForked && !timeout { if peers := pm.peers.Len(); peers != 1 { t.Fatalf("peer count mismatch: have %d, want %d", peers, 1) } } else { if peers := pm.peers.Len(); peers != 0 { t.Fatalf("peer count mismatch: have %d, want %d", peers, 0) } } }