github.com/annchain/OG@v0.0.9/og/helper_test.go (about)

     1  // Copyright © 2019 Annchain Authors <EMAIL ADDRESS>
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  package og
    15  
    16  import (
    17  	"crypto/rand"
    18  	"fmt"
    19  	"github.com/annchain/OG/arefactor/og/types"
    20  	"github.com/annchain/OG/arefactor/ogcrypto"
    21  	"github.com/annchain/OG/debug/debuglog"
    22  	ogcrypto2 "github.com/annchain/OG/deprecated/ogcrypto"
    23  	"github.com/annchain/OG/og/downloader"
    24  	core2 "github.com/annchain/OG/ogcore/ledger"
    25  	"github.com/annchain/OG/ogcore/pool"
    26  	"github.com/annchain/OG/ogcore/state"
    27  	"github.com/annchain/OG/ogdb"
    28  	"github.com/annchain/OG/p2p"
    29  	"github.com/annchain/OG/p2p/onode"
    30  	"github.com/sirupsen/logrus"
    31  	"testing"
    32  )
    33  
    34  var (
    35  	testBankKey, _ = ogcrypto2.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    36  	testBank       = ogcrypto.PubkeyToAddress(testBankKey.PublicKey)
    37  	testNetworkId  = uint64(101)
    38  )
    39  
    40  // newTestProtocolManager creates a new protocol manager for testing purposes,
    41  // with the given number of blocks already known, and potential notification
    42  // channels for different events.
    43  func newTestHub(mode downloader.SyncMode) (*Hub, *ogdb.MemDatabase, error) {
    44  	var (
    45  		db               = ogdb.NewMemDatabase()
    46  		genesis, balance = core2.DefaultGenesis("genesis.json")
    47  		config           = core2.DagConfig{}
    48  		dag, _           = core2.NewDag(config, state.StateDBConfig{}, db, nil)
    49  	)
    50  	if err := dag.Init(genesis, balance); err != nil {
    51  		panic(err)
    52  	}
    53  	txConf := pool.DefaultTxPoolConfig()
    54  	txPool := &pool.TxPool{
    55  		NodeLogger: debuglog.NodeLogger{
    56  			Logger: logrus.StandardLogger(),
    57  		},
    58  		EventBus: nil,
    59  		Config:   txConf,
    60  		Dag:      dag,
    61  	}
    62  	txPool.InitDefault()
    63  	txPool.Init(genesis)
    64  
    65  	hubConf := DefaultHubConfig()
    66  	hub := NewHub(&hubConf)
    67  	/*
    68  		syncConf := DefaultSyncerConfig()
    69  		syncer := NewSyncer(&syncConf, hub)
    70  		verfier := &GraphVerifier{
    71  			Signer:       &ogcrypto.SignerSecp256k1{},
    72  			CryptoType:   ogcrypto.CryptoTypeSecp256k1,
    73  			Dag:          dag,
    74  			TxPool:       txPool,
    75  			MaxTxHash:    common.HexToHash("0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
    76  			MaxMinedHash: common.HexToHash("0x00000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
    77  		}
    78  
    79  		//bufConf := DefaultTxBufferConfig(syncer, txPool, dag, verfier)
    80  		//txBuffer := NewTxBuffer(bufConf)
    81  		//txBuffer.Hub = hub
    82  		//hub.TxBuffer = txBuffer
    83  
    84  		//dag.Start()
    85  		//txPool.Start()
    86  
    87  		//syncer.Start()
    88  		txBuffer.Start()
    89  	*/
    90  	if hub == nil {
    91  		return nil, nil, fmt.Errorf("hub init error")
    92  	}
    93  	hub.Start()
    94  
    95  	return hub, db, nil
    96  }
    97  
    98  // testPeer is a simulated peer to allow testing direct network calls.
    99  type testPeer struct {
   100  	net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
   101  	app *p2p.MsgPipeRW    // Application layer reader/writer to simulate the local side
   102  	*peer
   103  }
   104  
   105  // newTestPeer creates a new peer registered at the given protocol manager.
   106  func newTestPeer(name string, version int, h *Hub, shake bool) (*testPeer, <-chan error) {
   107  	// Create a Message pipe to communicate through
   108  	app, net := p2p.MsgPipe()
   109  
   110  	// Generate a random id and create the peer
   111  	var id onode.ID
   112  	rand.Read(id[:])
   113  
   114  	peer := newPeer(version, p2p.NewPeer(id, name, nil), net)
   115  
   116  	// Start the peer on a new thread
   117  	errc := make(chan error, 1)
   118  	go func() {
   119  		select {
   120  		case h.newPeerCh <- peer:
   121  			errc <- h.handle(peer)
   122  		case <-h.quitSync:
   123  			errc <- p2p.DiscQuitting
   124  		}
   125  	}()
   126  	tp := &testPeer{app: app, net: net, peer: peer}
   127  	// Execute any implicitly requested handshakes and return
   128  	if shake {
   129  		var (
   130  			currentStatus = h.StatusDataProvider.GetCurrentNodeStatus()
   131  			genesis       = currentStatus.GenesisBlock
   132  			head          = currentStatus.CurrentBlock
   133  			id            = currentStatus.CurrentId
   134  		)
   135  		tp.handshake(nil, id, head, genesis)
   136  	}
   137  	return tp, errc
   138  }
   139  
   140  // handshake simulates a trivial handshake that expects the same state from the
   141  // remote side as we are simulating locally.
   142  func (p *testPeer) handshake(t *testing.T, seqId uint64, head types.Hash, genesis types.Hash) {
   143  	msg := &og.StatusData{
   144  		ProtocolVersion: uint32(p.version),
   145  		NetworkId:       testNetworkId,
   146  		CurrentId:       seqId,
   147  		CurrentBlock:    head,
   148  		GenesisBlock:    genesis,
   149  	}
   150  	if err := p2p.ExpectMsg(p.app, message_archive.StatusMsg.Code(), msg); err != nil {
   151  		t.Fatalf("status recv: %v", err)
   152  	}
   153  	data, _ := msg.MarshalMsg(nil)
   154  	if err := p2p.Send(p.app, message_archive.StatusMsg.Code(), data); err != nil {
   155  		t.Fatalf("status send: %v", err)
   156  	}
   157  }
   158  
   159  // close terminates the local side of the peer, notifying the remote protocol
   160  // manager of termination.
   161  func (p *testPeer) close() {
   162  	p.app.Close()
   163  }
   164  
   165  func TestDatasize(t *testing.T) {
   166  	var r types.Hash
   167  	data, _ := r.MarshalMsg(nil)
   168  	if len(data) == r.Msgsize() {
   169  		t.Fatal("msg size not equal", "len Data", len(data), "msgSize", r.Msgsize())
   170  	}
   171  }