├── doc.md ├── processor ├── miner │ ├── consensus │ │ ├── consensus_state_test.go │ │ ├── consensus_timer_test.go │ │ ├── mock │ │ │ ├── fakerticker.go │ │ │ ├── sync.go │ │ │ ├── heartbeat.go │ │ │ └── bcproducer.go │ │ ├── log.go │ │ └── sortition_test.go │ ├── appblockchain │ │ ├── subscribers.go │ │ ├── log.go │ │ └── mail.go │ ├── txprocessor │ │ └── log.go │ ├── injector.go │ └── wire_gen.go ├── controller │ ├── setup_test.go │ ├── mocks │ │ ├── heartbeatEnabler.go │ │ ├── iReshardHandler.go │ │ └── iShardRouter.go │ ├── internal │ │ ├── model.go │ │ ├── log.go │ │ └── mail.go │ ├── log.go │ ├── shardproxies.go │ ├── rpchandler.go │ └── README.md ├── shared │ ├── chain │ │ ├── interface.go │ │ ├── injector.go │ │ ├── mail.go │ │ ├── log.go │ │ └── events.go │ ├── smartcontractdatastore │ │ ├── log.go │ │ └── interface.go │ ├── blockconfirmproductor │ │ └── log.go │ ├── message │ │ ├── pubsub_topics.go │ │ └── pubsub.go │ └── txpool │ │ └── interface.go ├── storagenode │ ├── log.go │ ├── depositmanager_test.go │ ├── injector.go │ ├── wire_gen.go │ └── mail.go └── sync │ ├── mail.go │ ├── log.go │ ├── synctimer_test.go │ ├── synctimer.go │ └── state.go ├── mvvm ├── main.wasm ├── reduce.wasm ├── test_exec.wasm ├── test_init.wasm ├── rlp │ ├── Makefile │ └── README.md ├── util.go ├── table.go ├── test_init.wast ├── logger.go ├── deploymvvm_test.go ├── gas.go └── wasm_func.go ├── rpc ├── rpcserver │ ├── websocket │ │ ├── .travis.yml │ │ ├── AUTHORS │ │ ├── .gitignore │ │ ├── bench_test.go │ │ ├── util_test.go │ │ ├── server_test.go │ │ ├── LICENSE │ │ ├── util.go │ │ ├── json.go │ │ └── json_test.go │ └── mocks │ │ └── rpcHandler.go ├── rpcclient │ ├── CONTRIBUTORS │ ├── examples │ │ └── bitcoincorehttp │ │ │ ├── README.md │ │ │ └── main.go │ └── log.go └── btcjson │ ├── CONTRIBUTORS │ ├── chainsvrwsresults.go │ ├── btcdextresults.go │ ├── mtvblockinfo.go │ ├── mtvshardinfo.go │ ├── chainsvrwsresults_test.go │ ├── btcdextresults_test.go │ └── export_test.go ├── multivac_dev.conf ├── model ├── wire │ ├── testdata │ │ └── megatx.bin.bz2 │ ├── reduceouts.go │ ├── updateouts.go │ ├── MsgFetchEncode.go │ ├── smartcontract_test.go │ ├── msgstartnet.go │ ├── error.go │ ├── msg_resendsyncreq.go │ ├── msg_resendsyncreq_test.go │ ├── consensus_conmmon_test.go │ ├── msg_tx_batch.go │ ├── msgfetchtxs.go │ ├── update_shards_message.go │ ├── msgreturndeposit.go │ ├── msgfetchinit.go │ ├── msgfetchdeposit.go │ ├── msg_returntxs_test.go │ ├── msgverack.go │ ├── msg_syncblock_test.go │ ├── msg_returninit.go │ ├── msgfetchsmartcontractinfo.go │ ├── msg_syncslimblock_test.go │ ├── msgheartbeat.go │ ├── msg_syncblock.go │ ├── new_round_start_message.go │ ├── msggetaddr.go │ ├── protocol_test.go │ ├── fakemessage_test.go │ ├── msgrelayhash.go │ ├── msg_syncslimblock.go │ ├── msg_syncheaders.go │ └── msg_syncreq_test.go ├── chaincfg │ ├── chainhash │ │ ├── doc.go │ │ ├── hashfuncs.go │ │ └── README.md │ ├── reducekey │ │ ├── reducepublickey.go │ │ └── reduceprivatekey.go │ ├── genesis │ │ ├── README │ │ ├── publickeys.go │ │ ├── privatekeys.go.template │ │ ├── shard.go.template │ │ ├── pk.json │ │ └── genesis_test.go │ ├── signature │ │ └── signature_test.go │ └── params_test.go ├── shard │ └── shardlist.go └── merkle │ ├── log.go │ ├── ram_node_map.go │ ├── ram_merkle_node.go │ └── common_test.go ├── testnet └── cmdregistertest_test.go ├── interface ├── iconsensus │ ├── listener.go │ ├── depositefetcher.go │ ├── sortitionor.go │ └── consensus.go ├── peer │ └── msgRelyRules.go ├── iheartbeat │ └── heartbeat.go ├── ipeer │ └── msg_relay_rules.go ├── iabci │ ├── fetcher.go │ └── appblockchain.go ├── isysapi │ └── docs.md ├── icontroller │ └── shardcontroller.go ├── imvvm │ └── mvvm.go ├── idepositpool │ └── depositpool.go ├── isync │ └── syncmanager.go ├── itxprocessor │ └── txprocessor.go └── istate │ └── state.go ├── base ├── go-socks │ ├── README.md │ ├── socks │ │ ├── addr.go │ │ └── conn.go │ └── LICENSE ├── db │ └── batch.go ├── util │ ├── shard.go │ └── dbUtil.go ├── rlp │ ├── doc.go │ └── encoder_example_test.go └── vrf │ └── vrf.go ├── run.sh ├── testutil ├── package.go └── mockheart.go ├── configs ├── limits │ ├── limits_windows.go │ ├── limits_plan9.go │ └── limits_unix.go ├── params │ ├── flags.go │ ├── shard.go │ └── params.go └── config │ └── config_test.go ├── logger ├── btclog │ ├── .travis.yml │ ├── .gitignore │ ├── LICENSE │ ├── doc.go │ ├── README.md │ └── goclean.sh └── level.go ├── peer-server.iml ├── server ├── autoupdater │ ├── utils.go │ ├── poller_test.go │ └── poller.go └── shutdown │ └── signalsigterm.go ├── pos ├── heartbeat │ ├── mail.go │ ├── log.go │ ├── mocks │ │ ├── fakerticker.go │ │ └── mockbroadcast.go │ └── README.md └── depositpool │ ├── log.go │ └── mail.go ├── p2p ├── connection │ └── interface.go ├── connmgr │ ├── doc.go │ ├── log.go │ └── README.md ├── addrmgr │ ├── cov_report.sh │ ├── log.go │ └── internal_test.go ├── btcutil │ └── net.go └── peer │ ├── export_test.go │ └── rules.go ├── LICENSE ├── install └── monitoring └── multivac.rules.yaml /doc.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /processor/miner/consensus/consensus_state_test.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | -------------------------------------------------------------------------------- /processor/miner/consensus/consensus_timer_test.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | -------------------------------------------------------------------------------- /mvvm/main.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multivactech/MultiVAC/HEAD/mvvm/main.wasm -------------------------------------------------------------------------------- /mvvm/reduce.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multivactech/MultiVAC/HEAD/mvvm/reduce.wasm -------------------------------------------------------------------------------- /mvvm/test_exec.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multivactech/MultiVAC/HEAD/mvvm/test_exec.wasm -------------------------------------------------------------------------------- /mvvm/test_init.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multivactech/MultiVAC/HEAD/mvvm/test_init.wasm -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.1 5 | - 1.2 6 | - tip 7 | -------------------------------------------------------------------------------- /multivac_dev.conf: -------------------------------------------------------------------------------- 1 | ;Secure the RPC API by specifying the username and password. 2 | rpcuser=multivac 3 | rpcpass=multivac -------------------------------------------------------------------------------- /model/wire/testdata/megatx.bin.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multivactech/MultiVAC/HEAD/model/wire/testdata/megatx.bin.bz2 -------------------------------------------------------------------------------- /mvvm/rlp/Makefile: -------------------------------------------------------------------------------- 1 | CPP_FLAG=-std=c++11 -fPIC 2 | ALL: 3 | g++ $(CPP_FLAG) -shared -o librlp.so RLP.cpp 4 | 5 | clean: 6 | rm *.so *.o -------------------------------------------------------------------------------- /testnet/cmdregistertest_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestListCommands(t *testing.T) { 8 | listCommands() 9 | } 10 | -------------------------------------------------------------------------------- /interface/iconsensus/listener.go: -------------------------------------------------------------------------------- 1 | package iconsensus 2 | 3 | // CEShardStateListener is used to control the status of consensus. 4 | type CEShardStateListener interface { 5 | OnShardDisabled() 6 | } 7 | -------------------------------------------------------------------------------- /mvvm/util.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package mvvm 9 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of Gorilla WebSocket authors for copyright 2 | # purposes. 3 | # 4 | # Please keep the list sorted. 5 | 6 | Gary Burd 7 | Joachim Bauch 8 | 9 | -------------------------------------------------------------------------------- /base/go-socks/README.md: -------------------------------------------------------------------------------- 1 | SOCKS5 Proxy Package for Go 2 | =========================== 3 | 4 | Documentation: 5 | 6 | License 7 | ------- 8 | 9 | 3-clause BSD. See LICENSE file. 10 | -------------------------------------------------------------------------------- /model/chaincfg/chainhash/doc.go: -------------------------------------------------------------------------------- 1 | // Package chainhash provides abstracted hash functionality. 2 | // 3 | // This package provides a generic hash type and associated functions that 4 | // allows the specific hash algorithm to be abstracted. 5 | package chainhash 6 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # This script is support restart for testctl 3 | 4 | go install 5 | go install ../testing-tools 6 | go install ./testnet 7 | 8 | # Only delete test log 9 | rm -rf test 10 | rm -rf test/storage-*/logs/ 11 | 12 | # If need restore previous data from disk,should add "--restart" 13 | testing-tools -------------------------------------------------------------------------------- /testutil/package.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package testutil 9 | 10 | // Package name for testing 11 | const ( 12 | Deposit = "deposit" 13 | ) 14 | -------------------------------------------------------------------------------- /configs/limits/limits_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package limits 6 | 7 | // SetLimits is a no-op on Windows since it's not required there. 8 | func SetLimits() error { 9 | return nil 10 | } 11 | -------------------------------------------------------------------------------- /processor/controller/setup_test.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/configs/config" 5 | ) 6 | 7 | func createMockedRootController(isStorageNode bool) *RootController { 8 | cfg := &config.Config{ 9 | StorageNode: isStorageNode, 10 | } 11 | return &RootController{ 12 | cfg: cfg, 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /configs/limits/limits_plan9.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package limits 6 | 7 | // SetLimits is a no-op on Plan 9 due to the lack of process accounting. 8 | func SetLimits() error { 9 | return nil 10 | } 11 | -------------------------------------------------------------------------------- /interface/peer/msgRelyRules.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package isync 6 | 7 | // MsgRelyRule is used to deal with relay message.It seems useless. 8 | type MsgRelyRule interface { 9 | } 10 | -------------------------------------------------------------------------------- /logger/btclog/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - 1.7.x 4 | - 1.8.x 5 | sudo: false 6 | install: 7 | - go get -d -t -v ./... 8 | - go get -v golang.org/x/tools/cmd/cover 9 | - go get -v github.com/bradfitz/goimports 10 | - go get -v github.com/golang/lint/golint 11 | script: 12 | - export PATH=$PATH:$HOME/gopath/bin 13 | - ./goclean.sh 14 | -------------------------------------------------------------------------------- /interface/iheartbeat/heartbeat.go: -------------------------------------------------------------------------------- 1 | package iheartbeat 2 | 3 | import "github.com/multivactech/MultiVAC/model/wire" 4 | 5 | // HeartBeat is used to deal with heartbeat message. 6 | type HeartBeat interface { 7 | Has(pk []byte) bool 8 | PerceivedCount() int 9 | Start() 10 | Stop() 11 | CheckConfirmation(confirmation *wire.MsgBlockConfirmation) bool 12 | } 13 | -------------------------------------------------------------------------------- /model/chaincfg/reducekey/reducepublickey.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package reducekey 6 | 7 | // ReducePublicKey is the public key of ReducePrivateKey. 8 | var ReducePublicKey = ReducePrivateKey.Public() 9 | -------------------------------------------------------------------------------- /model/chaincfg/genesis/README: -------------------------------------------------------------------------------- 1 | To update shard lists, run script.py. Usage: 2 | 3 | python script.py 4 | 5 | e.g. 6 | python script.py 7 7 | 8 | It will generate 2<<7 = 128 shards. 9 | 10 | This script also generates private keys and public keys for each shard. So 11 | the more shards, the longer it will take. 12 | 13 | Maximum prefix length is 32. 14 | -------------------------------------------------------------------------------- /peer-server.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /processor/miner/appblockchain/subscribers.go: -------------------------------------------------------------------------------- 1 | package appblockchain 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/processor/shared/message" 5 | ) 6 | 7 | // Recv implements the message.Recv interface to subscribe events. 8 | func (abci *appBlockChain) Recv(e message.Event) { 9 | switch e.Topic { 10 | case message.EvtLedgerFallBehind: 11 | abci.fetchNewLedger() 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /server/autoupdater/utils.go: -------------------------------------------------------------------------------- 1 | package autoupdater 2 | 3 | import ( 4 | "io/ioutil" 5 | "net/http" 6 | ) 7 | 8 | func download(url string) ([]byte, error) { 9 | res, err := http.Get(url) 10 | if err != nil { 11 | return nil, err 12 | } 13 | body, err := ioutil.ReadAll(res.Body) 14 | if err != nil { 15 | return nil, err 16 | } 17 | res.Body.Close() 18 | 19 | return body, nil 20 | } 21 | -------------------------------------------------------------------------------- /logger/btclog/.gitignore: -------------------------------------------------------------------------------- 1 | # Temp files 2 | *~ 3 | 4 | # Log files 5 | *.log 6 | 7 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 8 | *.o 9 | *.a 10 | *.so 11 | 12 | # Folders 13 | _obj 14 | _test 15 | 16 | # Architecture specific extensions/prefixes 17 | *.[568vq] 18 | [568vq].out 19 | 20 | *.cgo1.go 21 | *.cgo2.c 22 | _cgo_defun.c 23 | _cgo_gotypes.go 24 | _cgo_export.* 25 | 26 | _testmain.go 27 | 28 | *.exe 29 | -------------------------------------------------------------------------------- /processor/controller/mocks/heartbeatEnabler.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v1.0.0. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import mock "github.com/stretchr/testify/mock" 6 | 7 | // MockedHeartbeatEnabler is an autogenerated mock type for the MockedHeartbeatEnabler type 8 | type MockedHeartbeatEnabler struct { 9 | mock.Mock 10 | } 11 | 12 | // Start provides a mock function with given fields: 13 | func (_m *MockedHeartbeatEnabler) Start() { 14 | _m.Called() 15 | } 16 | -------------------------------------------------------------------------------- /model/wire/reduceouts.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | // ReduceAction is used to deal with the issue of cross-shard-update 8 | type ReduceAction struct { 9 | ToBeReducedOut *OutPoint // OutState that needs to be merged 10 | API string // ReduceAction needs to call the smart contract API 11 | } 12 | -------------------------------------------------------------------------------- /mvvm/table.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package mvvm 9 | 10 | const ( 11 | // defaultTableSize shows the default size of table for a new MVVM. 12 | // The table is used for storing the "indirect call" function. 13 | // For now defaultTableSize is set as 65536. 14 | defaultTableSize = 1 << 16 15 | ) 16 | -------------------------------------------------------------------------------- /interface/iconsensus/depositefetcher.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package iconsensus 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/shard" 9 | ) 10 | 11 | // DepositFetcher get deposited information. 12 | type DepositFetcher interface { 13 | GetDepositUnit(pk []byte, round int32, index shard.Index) uint32 14 | } 15 | -------------------------------------------------------------------------------- /model/wire/updateouts.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/merkle" 9 | ) 10 | 11 | // UpdateAction 是矿工根据计算结果对存储节点发送的修改数据的请求 12 | type UpdateAction struct { 13 | OriginOut *OutState 14 | OriginOutProof *merkle.MerklePath 15 | NewOut *OutState 16 | } 17 | -------------------------------------------------------------------------------- /pos/heartbeat/mail.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package heartbeat 9 | 10 | import "github.com/multivactech/MultiVAC/processor/shared/message" 11 | 12 | const ( 13 | evtReceiveReq message.EventTopic = iota 14 | evtHasReq 15 | evtPerceivedCountReq 16 | evtStartReq 17 | evtStopReq 18 | evtCheckConfirmation 19 | ) 20 | -------------------------------------------------------------------------------- /p2p/connection/interface.go: -------------------------------------------------------------------------------- 1 | package connection 2 | 3 | import "github.com/multivactech/MultiVAC/model/shard" 4 | 5 | // Connector is used for inject. 6 | type Connector interface { 7 | UpdatePeerInfo([]shard.Index) 8 | } 9 | 10 | // BroadcastParams defines the broadcast params. 11 | type BroadcastParams struct { 12 | ToNode toNodeType 13 | ToShard shard.Index 14 | IncludeSelf bool 15 | //exclPeers []*ConnPeer 16 | // todo(ymh):seems to unuse from golangci-lint. 17 | // targetShards []shard.Index 18 | } 19 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/bench_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "testing" 9 | ) 10 | 11 | func BenchmarkMaskBytes(b *testing.B) { 12 | var key [4]byte 13 | data := make([]byte, 1024) 14 | pos := 0 15 | for i := 0; i < b.N; i++ { 16 | pos = maskBytes(key, pos, data) 17 | } 18 | b.SetBytes(int64(len(data))) 19 | } 20 | -------------------------------------------------------------------------------- /processor/shared/chain/interface.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package chain 9 | 10 | // SyncTrigger is a interface that contains a method called MayBeSync 11 | // which notifies SyncManager to request a sync, whether or not a sync will actually happen depending on internal logic. 12 | type SyncTrigger interface { 13 | MaybeSync() 14 | } 15 | -------------------------------------------------------------------------------- /base/db/batch.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package db 6 | 7 | import ( 8 | "github.com/syndtr/goleveldb/leveldb" 9 | ) 10 | 11 | type batchImpl struct { 12 | batch *leveldb.Batch 13 | } 14 | 15 | func (bt *batchImpl) Put(key []byte, value []byte) { 16 | bt.batch.Put(key, value) 17 | } 18 | 19 | func (bt *batchImpl) Len() int { 20 | return bt.batch.Len() 21 | } 22 | -------------------------------------------------------------------------------- /p2p/connmgr/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package connmgr implements a generic Bitcoin network connection manager. 7 | 8 | Connection Manager Overview 9 | 10 | Connection Manager handles all the general connection concerns such as 11 | maintaining a set number of outbound connections, sourcing peers, banning, 12 | limiting max connections, tor lookup, etc. 13 | */ 14 | package connmgr 15 | -------------------------------------------------------------------------------- /mvvm/test_init.wast: -------------------------------------------------------------------------------- 1 | ;;; // origin code (C++): 2 | ;;; 3 | ;;; char* init(int n) { 4 | ;;; char *arr = new char[26 + 1]; 5 | ;;; arr = "abcdefghijklmnopqrstuvwxyz"; 6 | ;;; return arr+n; 7 | ;;; } 8 | ;;; 9 | 10 | (module 11 | (table 0 anyfunc) 12 | (memory $0 1) 13 | (data (i32.const 16) "abcdefghijklmnopqrstuvwxyz\00") 14 | (export "memory" (memory $0)) 15 | (export "_Z4initi" (func $_Z4initi)) 16 | (func $_Z4initi (; 0 ;) (param $0 i32) (result i32) 17 | (i32.add 18 | (get_local $0) 19 | (i32.const 16) 20 | ) 21 | ) 22 | ) 23 | -------------------------------------------------------------------------------- /rpc/rpcclient/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This is the list of people who have contributed code to the repository. 2 | # 3 | # Names should be added to this file only after verifying that the individual 4 | # or the individual's organization has agreed to the LICENSE. 5 | # 6 | # Names should be added to this file like so: 7 | # Name 8 | 9 | Dave Collins 10 | Geert-Johan Riemer 11 | Josh Rickmar 12 | Michalis Kargakis 13 | Ruben de Vries /dev/null 2>&1 11 | if [ $? -ne 0 ]; then 12 | echo >&2 "This script requires the gocov tool." 13 | echo >&2 "You may obtain it with the following command:" 14 | echo >&2 "go get github.com/axw/gocov/gocov" 15 | exit 1 16 | fi 17 | gocov test | gocov report 18 | -------------------------------------------------------------------------------- /p2p/btcutil/net.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !appengine 6 | 7 | package btcutil 8 | 9 | import ( 10 | "net" 11 | ) 12 | 13 | // interfaceAddrs returns a list of the system's network interface addresses. 14 | // It is wrapped here so that we can substitute it for other functions when 15 | // building for systems that do not allow access to net.InterfaceAddrs(). 16 | func interfaceAddrs() ([]net.Addr, error) { 17 | return net.InterfaceAddrs() 18 | } 19 | -------------------------------------------------------------------------------- /processor/controller/internal/model.go: -------------------------------------------------------------------------------- 1 | package internal 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/base/vrf" 5 | "github.com/multivactech/MultiVAC/interface/iconsensus" 6 | "github.com/multivactech/MultiVAC/model/shard" 7 | ) 8 | 9 | var ( 10 | // DefaultShard is the default shard when no sharding is enabled. 11 | DefaultShard = shard.IDToShardIndex(0) 12 | ) 13 | 14 | // ValidationInfo wraps the identity validation relevant contributors. 15 | type ValidationInfo struct { 16 | Selector iconsensus.Sortitionor 17 | Pk []byte 18 | Sk []byte 19 | Vrf vrf.VRF 20 | } 21 | -------------------------------------------------------------------------------- /server/shutdown/signalsigterm.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Copyright (c) 2016 The btcsuite developers 6 | // Use of this source code is governed by an ISC 7 | // license that can be found in the LICENSE file. 8 | 9 | // +build darwin dragonfly freebsd linux netbsd openbsd solaris 10 | 11 | package shutdown 12 | 13 | import ( 14 | "os" 15 | "syscall" 16 | ) 17 | 18 | func init() { 19 | interruptSignals = []os.Signal{syscall.SIGTERM} 20 | } 21 | -------------------------------------------------------------------------------- /processor/shared/chain/mail.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package chain 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/shard" 12 | "github.com/multivactech/MultiVAC/model/wire" 13 | ) 14 | 15 | type triggerRequest struct { 16 | shard shard.Index 17 | trigger SyncTrigger 18 | } 19 | 20 | type saveSlimBlockRequest struct { 21 | toshard shard.Index 22 | shard shard.Index 23 | height wire.BlockHeight 24 | } 25 | -------------------------------------------------------------------------------- /processor/miner/txprocessor/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package txprocessor 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/logger" 12 | "github.com/multivactech/MultiVAC/logger/btclog" 13 | ) 14 | 15 | var log btclog.Logger 16 | 17 | func init() { 18 | var exists bool 19 | log, exists = logger.GetLogger(logger.TxProcessorTag) 20 | if !exists { 21 | panic("Fail to get logger for txprocessor package") 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /model/shard/shardlist.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package shard 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/configs/params" 9 | ) 10 | 11 | func generateShardList() []Index { 12 | shardList := []Index{} 13 | for i := 0; i < (1 << params.GenesisShardPrefixLength); i++ { 14 | shardList = append(shardList, IDToShardIndex(uint32(i))) 15 | } 16 | return shardList 17 | } 18 | 19 | // ShardList is the list of shard index. 20 | var ShardList = generateShardList() 21 | -------------------------------------------------------------------------------- /pos/heartbeat/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package heartbeat 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var logBackend *btclog.Backend 20 | 21 | func init() { 22 | logBackend = logger.BackendLogger() 23 | } 24 | -------------------------------------------------------------------------------- /interface/ipeer/msg_relay_rules.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | //This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package ipeer 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/wire" 9 | ) 10 | 11 | // MsgRelayRule is used to deal with relay message. 12 | type MsgRelayRule interface { 13 | // Filter will filter the message, it should follow the rules below: 14 | // 1.If an error occurs, return the original message. 15 | // 2.If the message does not need to be relayed, return nil. 16 | Filter(msg wire.Message) (wire.Message, error) 17 | } 18 | -------------------------------------------------------------------------------- /processor/shared/smartcontractdatastore/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package smartcontractdatastore 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/logger" 12 | "github.com/multivactech/MultiVAC/logger/btclog" 13 | ) 14 | 15 | var log btclog.Logger 16 | 17 | func init() { 18 | var exists bool 19 | log, exists = logger.GetLogger(logger.SmartContractDataStoreTag) 20 | if !exists { 21 | panic("Fail to get logger for smartContractDataStore package") 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /processor/shared/chain/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package chain 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/logger" 12 | "github.com/multivactech/MultiVAC/logger/btclog" 13 | ) 14 | 15 | // log is a logger that is initialized with no output filters. This 16 | // means the package will not perform any logging by default until the caller 17 | // requests it. 18 | var logBackend *btclog.Backend 19 | 20 | func init() { 21 | logBackend = logger.BackendLogger() 22 | } 23 | -------------------------------------------------------------------------------- /processor/storagenode/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package storagenode 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var logBackend *btclog.Backend 20 | 21 | func init() { 22 | logBackend = logger.BackendLogger() 23 | } 24 | -------------------------------------------------------------------------------- /rpc/btcjson/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This is the list of people who have contributed code to the repository. 2 | # 3 | # Names should be added to this file only after verifying that the individual 4 | # or the individual's organization has agreed to the LICENSE. 5 | # 6 | # Names should be added to this file like so: 7 | # Name 8 | 9 | John C. Vernaleo 10 | Dave Collins 11 | Owain G. Ainsworth 12 | David Hill 13 | Josh Rickmar 14 | Andreas Metsälä 15 | Francis Lam 16 | Geert-Johan Riemer 17 | -------------------------------------------------------------------------------- /base/go-socks/socks/addr.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Samuel Stauffer. All rights reserved. 2 | // Use of this source code is governed by a 3-clause BSD 3 | // license that can be found in the LICENSE file. 4 | 5 | package socks 6 | 7 | import "fmt" 8 | 9 | // ProxiedAddr is used for proxy address. 10 | type ProxiedAddr struct { 11 | Net string 12 | Host string 13 | Port int 14 | } 15 | 16 | // Network returns the net of ProxiedAddr. 17 | func (a *ProxiedAddr) Network() string { 18 | return a.Net 19 | } 20 | 21 | // String will print the ip address and port of proxied address. 22 | func (a *ProxiedAddr) String() string { 23 | return fmt.Sprintf("%s:%d", a.Host, a.Port) 24 | } 25 | -------------------------------------------------------------------------------- /interface/iabci/fetcher.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package iabci 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/shard" 9 | ) 10 | 11 | // Fetcher is an interface to dealing with request fetching information from storage node. 12 | type Fetcher interface { 13 | // Request a given number of transactions from storage node. 14 | FetchTransactions(number int, hashList []uint32, shard shard.Index) 15 | // Request data for abci initalization from storage node 16 | FetchInitData(shard shard.Index) 17 | } 18 | -------------------------------------------------------------------------------- /processor/miner/appblockchain/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package appblockchain 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var logBackend *btclog.Backend 20 | 21 | func init() { 22 | logBackend = logger.BackendLogger() 23 | } 24 | -------------------------------------------------------------------------------- /processor/shared/blockconfirmproductor/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package blockconfirmproductor 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var logBackend *btclog.Backend 20 | 21 | func init() { 22 | logBackend = logger.BackendLogger() 23 | } -------------------------------------------------------------------------------- /processor/controller/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package controller 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var rootCtrlLogger btclog.Logger 20 | 21 | func init() { 22 | rootCtrlLogger, _ = logger.GetLogger(logger.RootControllerLoggerTag) 23 | } 24 | -------------------------------------------------------------------------------- /p2p/peer/export_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | This test file is part of the peer package rather than than the peer_test 7 | package so it can bridge access to the internals to properly test cases which 8 | are either not possible or can't reliably be tested via the public interface. 9 | The functions are only exported while the tests are being run. 10 | */ 11 | 12 | package peer 13 | 14 | // TstAllowSelfConns allows the test package to allow self connections by 15 | // disabling the detection logic. 16 | func TstAllowSelfConns() { 17 | allowSelfConns = true 18 | } 19 | -------------------------------------------------------------------------------- /interface/iabci/appblockchain.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package iabci 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/wire" 9 | ) 10 | 11 | // AppBlockChain is used to manage merkle tree. 12 | type AppBlockChain interface { 13 | VerifyBlock(block *wire.MsgBlock) error 14 | ProposeBlock(pk []byte, sk []byte) (*wire.MsgBlock, error) 15 | ProposeAndAcceptEmptyBlock(height int64) (*wire.BlockHeader, error) 16 | AcceptBlock(block *wire.MsgBlock) error 17 | Start(prevReshardheader *wire.BlockHeader) 18 | Stop() 19 | PreStart() 20 | } 21 | -------------------------------------------------------------------------------- /pos/heartbeat/mocks/fakerticker.go: -------------------------------------------------------------------------------- 1 | package mocks 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | // FakeTicker for easier testing. 8 | type FakeTicker struct { 9 | C chan time.Time 10 | Stopped bool 11 | } 12 | 13 | // Chan implement ticker interface 14 | func (ft *FakeTicker) Chan() <-chan time.Time { 15 | return ft.C 16 | } 17 | 18 | // Stop implement ticker interface 19 | func (ft *FakeTicker) Stop() { 20 | ft.Stopped = true 21 | } 22 | 23 | // Tick sends the tick time to the ticker channel after every period. 24 | // Tick events are discarded if the underlying ticker channel does 25 | // not have enough capacity. 26 | func (ft *FakeTicker) Tick() { 27 | if ft.Stopped { 28 | return 29 | } 30 | ft.C <- time.Now() 31 | } 32 | -------------------------------------------------------------------------------- /p2p/connmgr/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Copyright (c) 2016 The btcsuite developers 6 | // Use of this source code is governed by an ISC 7 | // license that can be found in the LICENSE file. 8 | 9 | package connmgr 10 | 11 | import ( 12 | "github.com/multivactech/MultiVAC/logger" 13 | "github.com/multivactech/MultiVAC/logger/btclog" 14 | ) 15 | 16 | var log btclog.Logger 17 | 18 | func init() { 19 | var exists bool 20 | log, exists = logger.GetLogger(logger.ConnmgrLoggerTag) 21 | if !exists { 22 | panic("Fail to get logger for connmgr package") 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /p2p/addrmgr/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Copyright (c) 2013-2014 The btcsuite developers 6 | // Use of this source code is governed by an ISC 7 | // license that can be found in the LICENSE file. 8 | 9 | package addrmgr 10 | 11 | import ( 12 | "github.com/multivactech/MultiVAC/logger" 13 | "github.com/multivactech/MultiVAC/logger/btclog" 14 | ) 15 | 16 | var log btclog.Logger 17 | 18 | func init() { 19 | var exists bool 20 | log, exists = logger.GetLogger(logger.AddrmgrLoggerTag) 21 | if !exists { 22 | panic("Fail to get logger for addrmgr package") 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /processor/sync/mail.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package sync 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/configs/config" 12 | "github.com/multivactech/MultiVAC/p2p/connection" 13 | "github.com/multivactech/MultiVAC/processor/shared/message" 14 | ) 15 | 16 | const ( 17 | evtMsg message.EventTopic = iota 18 | evtAddPeer 19 | evtDonePeer 20 | evtSyncReq 21 | ) 22 | 23 | type peerMail struct { 24 | connPeer *connection.ConnPeer 25 | nodeType config.NodeType 26 | } 27 | 28 | type storageMissInfo struct { 29 | } 30 | 31 | type syncReq struct{} 32 | -------------------------------------------------------------------------------- /mvvm/logger.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2016 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package mvvm 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var log btclog.Logger 20 | 21 | func init() { 22 | var exists bool 23 | log, exists = logger.GetLogger(logger.VirtualMachineTag) 24 | if !exists { 25 | panic("Fail to get logger for mvvm package") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /rpc/btcjson/chainsvrwsresults.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2017 The btcsuite developers 2 | // Copyright (c) 2015-2017 The Decred developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package btcjson 7 | 8 | // SessionResult models the data from the session command. 9 | type SessionResult struct { 10 | SessionID uint64 `json:"sessionid"` 11 | } 12 | 13 | // RescannedBlock contains the hash and all discovered transactions of a single 14 | // rescanned block. 15 | // 16 | // NOTE: This is a btcsuite extension ported from 17 | // github.com/decred/dcrd/dcrjson. 18 | type RescannedBlock struct { 19 | Hash string `json:"hash"` 20 | Transactions []string `json:"transactions"` 21 | } 22 | -------------------------------------------------------------------------------- /mvvm/rlp/README.md: -------------------------------------------------------------------------------- 1 | # C++ RLP Encoding/Decoding Library For MultiVAC 2 | 3 | ## 1. Introduce 4 | 5 | The library is the encoding/decoding tool for MVVM (MultiVAC Virtual Machine). 6 | 7 | The library implements the encoding method for the input data structure *mvvmInput* and for the output data structure *mvvmOutput*. 8 | 9 | The library mainly depends on `libdevcore` library in project [aleth](https://github.com/ethereum/aleth). 10 | 11 | ## 2. Using the tool 12 | 13 | The required C++ environment is listed here: 14 | 15 | - C++11/C++17; 16 | - STL; 17 | - Boost; 18 | - Aleth (included here). 19 | 20 | ## 3. Test 21 | 22 | ```C++ 23 | cd mvvm/rlp/ 24 | g++ -std=c++11 -o main.out test_rlp.cpp RLP.cpp mvvm_inout.cpp 25 | ./main.out 26 | rm ./main.out 27 | ``` 28 | -------------------------------------------------------------------------------- /model/chaincfg/genesis/publickeys.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package genesis 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/chaincfg/signature" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | ) 14 | 15 | func publicKeys() map[shard.Index]signature.PublicKey { 16 | keys := make(map[shard.Index]signature.PublicKey) 17 | for _, shard := range shard.ShardList { 18 | keys[shard] = GenesisPrivateKeys[shard].Public() 19 | } 20 | return keys 21 | } 22 | 23 | // GenesisPublicKeys contains all genesis public keys 24 | var GenesisPublicKeys = publicKeys() 25 | -------------------------------------------------------------------------------- /model/chaincfg/reducekey/reduceprivatekey.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package reducekey 6 | 7 | import "github.com/multivactech/MultiVAC/model/chaincfg/signature" 8 | 9 | // ReducePrivateKey is used to sign reduce tx 10 | var ReducePrivateKey = signature.PrivateKey{ 11 | 255, 255, 43, 85, 60, 46, 148, 248, 12 | 168, 237, 186, 87, 135, 113, 87, 80, 13 | 53, 64, 172, 200, 43, 244, 45, 32, 14 | 204, 179, 235, 117, 248, 232, 62, 47, 15 | 45, 89, 120, 152, 41, 6, 10, 73, 16 | 40, 94, 5, 169, 144, 164, 55, 171, 17 | 141, 246, 2, 205, 223, 55, 200, 116, 18 | 122, 243, 232, 176, 135, 90, 67, 122, 19 | } 20 | -------------------------------------------------------------------------------- /model/merkle/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package merkle 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var log btclog.Logger 20 | 21 | func init() { 22 | var exists bool 23 | log, exists = logger.GetLogger(logger.AddrmgrLoggerTag) 24 | if !exists { 25 | panic("Fail to get logger for merkle package") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /processor/sync/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package sync 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/logger" 12 | "github.com/multivactech/MultiVAC/logger/btclog" 13 | ) 14 | 15 | // log is a logger that is initialized with no output filters. This 16 | // means the package will not perform any logging by default until the caller 17 | // requests it. 18 | var log btclog.Logger 19 | 20 | func init() { 21 | var exists bool 22 | log, exists = logger.GetLogger(logger.SyncLoggerTag) 23 | if !exists { 24 | panic("Fail to get logger for sync package") 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /interface/isysapi/docs.md: -------------------------------------------------------------------------------- 1 | ## 交易类型说明 2 | 3 | 该文档用于说明不同类型交易的参数及介绍,持续更新 4 | 5 | ### 普通交易 6 | 符合`Utxo`模型的区块链交易,由输入(txIn)和输出(txOut)构成,txIn是前一笔交易的txOut,在下文中普通交易产生的txOut统称为`Out` 7 | 8 | #### TransferParams 9 | - To:交易发送的目标账户地址 10 | - Shard:交易发送的目标分片号 11 | - Amount:交易的发送金额 12 | 13 | TransferParams是交易的基本参数,任何扩展交易类型必须包含上述三个字段 14 | 15 | ### 抵押交易 16 | 扩展自普通交易,输入为`Out`,生成特殊的抵押Out(以下简称`Dout`)用于用户抵押资金从而获得挖矿证明。 17 | 18 | #### DepositParams 19 | - BindingAddress:抵押绑定的用户地址 20 | 21 | 除了基本的交易参数外,BindingAddress用于记录该抵押交易所绑定的用户地址,该用户地址将会被授予挖矿权利 22 | 23 | ### 取款交易 24 | 扩展自普通交易,输入为`Dout`,生成特殊的取款Out(以下简称`Wout`)用于用户放弃抵押交易。 25 | 26 | #### WithdrawParams 27 | 同普通交易参数,无任何特殊限定 28 | 29 | ### 绑定交易 30 | 扩展自普通交易,输入为`Dout`,生成一个新的`Dout`,用于用户修改之前生效的抵押交易中的绑定地址。 31 | 32 | #### BindingParams 33 | - BindingAddress:新的绑定地址 -------------------------------------------------------------------------------- /model/chaincfg/genesis/privatekeys.go.template: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package genesis 9 | 10 | // This is file is generated by chaincfg/genesis/script.py 11 | // Please not edit manually, otherwise the change might get 12 | // override. 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/model/chaincfg/signature" 16 | "github.com/multivactech/MultiVAC/wire" 17 | ) 18 | 19 | func privateKeys() map[wire.ShardIndex]signature.PrivateKey { 20 | keys := make(map[wire.ShardIndex]signature.PrivateKey) 21 | %(keys_str)s 22 | return keys 23 | } 24 | 25 | var GenesisPrivateKeys = privateKeys() 26 | -------------------------------------------------------------------------------- /pos/depositpool/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package depositpool 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/logger" 12 | "github.com/multivactech/MultiVAC/logger/btclog" 13 | ) 14 | 15 | // log is a logger that is initialized with no output filters. This 16 | // means the package will not perform any logging by default until the caller 17 | // requests it. 18 | var log btclog.Logger 19 | var logBackend *btclog.Backend 20 | 21 | func init() { 22 | logBackend = logger.BackendLogger() 23 | log = logBackend.Logger(logger.DpoolLoggerTag) 24 | log.SetLevel(logger.DpoolLogLevel) 25 | } 26 | -------------------------------------------------------------------------------- /processor/controller/internal/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package internal 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var logBackend *btclog.Backend 20 | var rootCtrlLogger btclog.Logger 21 | 22 | func init() { 23 | logBackend = logger.BackendLogger() 24 | rootCtrlLogger, _ = logger.GetLogger(logger.RootControllerLoggerTag) 25 | } 26 | -------------------------------------------------------------------------------- /server/autoupdater/poller_test.go: -------------------------------------------------------------------------------- 1 | package autoupdater 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "net/http" 7 | "net/http/httptest" 8 | "net/url" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func createTestServer() *httptest.Server { 14 | version := 0 15 | return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 16 | fmt.Fprintf(w, "%d", version) 17 | version++ 18 | })) 19 | } 20 | 21 | func TestPoller(t *testing.T) { 22 | ts := createTestServer() 23 | url, _ := url.Parse(ts.URL) 24 | poller := newPoller(*url, 10*time.Millisecond) 25 | 26 | poller.Start() 27 | for i := 0; i < 10; i++ { 28 | if a := <-poller.changes; !bytes.Equal(a, []byte(fmt.Sprint(i))) { 29 | t.Errorf("Wrong polling result %s, should be %d", a, i) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /processor/shared/chain/events.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package chain 9 | 10 | import "github.com/multivactech/MultiVAC/processor/shared/message" 11 | 12 | const ( 13 | evtReceiveBlock message.EventTopic = iota 14 | evtReceiveHeader 15 | evtShardHeight 16 | evtBlockByShardAndHeight 17 | evtHeaderByShardAndHeight 18 | evtBlockByHash 19 | evtHeaderByHash 20 | evtShardHeaderHashes 21 | evtSetTrigger 22 | evtReceiveSlimBlock 23 | evtSlimBlockMsgByShardAndHeight 24 | evtSmartContractByAddress 25 | evtSmartContractCodeOut 26 | evtSmartContractShardInitOut 27 | evtReceiveSmartContractShardInitOut 28 | ) 29 | -------------------------------------------------------------------------------- /model/merkle/ram_node_map.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package merkle 9 | 10 | func createRAMNodeMap() iNodeMap { 11 | nm := &ramNodeMap{} 12 | nm.nodeMap = make(map[MerkleHash]iMerkleNode) 13 | return nm 14 | } 15 | 16 | type ramNodeMap struct { 17 | nodeMap map[MerkleHash]iMerkleNode 18 | } 19 | 20 | func (nm *ramNodeMap) set(key MerkleHash, value iMerkleNode) { 21 | nm.nodeMap[key] = value 22 | } 23 | 24 | func (nm *ramNodeMap) get(key MerkleHash) (iMerkleNode, bool) { 25 | v, e := nm.nodeMap[key] 26 | return v, e 27 | } 28 | 29 | func (nm *ramNodeMap) del(key MerkleHash) { 30 | delete(nm.nodeMap, key) 31 | } 32 | -------------------------------------------------------------------------------- /model/wire/MsgFetchEncode.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "encoding/gob" 5 | "io" 6 | 7 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 8 | ) 9 | 10 | // MsgFetchEncode is used to encode a fetch msg. 11 | type MsgFetchEncode struct { 12 | Msg Message 13 | ShardHeight int64 14 | UserAddress multivacaddress.Address 15 | } 16 | 17 | // BtcDecode decode the message. 18 | func (m *MsgFetchEncode) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 19 | decoder := gob.NewDecoder(r) 20 | return decoder.Decode(m) 21 | } 22 | 23 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 24 | func (m *MsgFetchEncode) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 25 | encoder := gob.NewEncoder(w) 26 | return encoder.Encode(*m) 27 | } 28 | -------------------------------------------------------------------------------- /processor/miner/consensus/mock/fakerticker.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import "time" 4 | 5 | // FakeTicker for easier testing. 6 | type FakeTicker struct { 7 | C chan time.Time 8 | Period time.Duration 9 | stopped bool 10 | now time.Time 11 | } 12 | 13 | // Chan implement ticker interface 14 | func (ft *FakeTicker) Chan() <-chan time.Time { 15 | return ft.C 16 | } 17 | 18 | // Stop implement ticker interface 19 | func (ft *FakeTicker) Stop() { 20 | ft.stopped = true 21 | } 22 | 23 | // Tick sends the tick time to the ticker channel after every period. 24 | // Tick events are discarded if the underlying ticker channel does 25 | // not have enough capacity. 26 | func (ft *FakeTicker) Tick() { 27 | if ft.stopped { 28 | return 29 | } 30 | 31 | ft.now = ft.now.Add(ft.Period) 32 | ft.C <- ft.now 33 | } 34 | -------------------------------------------------------------------------------- /logger/btclog/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2013-2014 Conformal Systems LLC. 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /rpc/btcjson/btcdextresults.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 The btcsuite developers 2 | // Copyright (c) 2015-2017 The Decred developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package btcjson 7 | 8 | // VersionResult models objects included in the version response. In the actual 9 | // result, these objects are keyed by the program or API name. 10 | // 11 | // NOTE: This is a btcsuite extension ported from 12 | // github.com/decred/dcrd/dcrjson. 13 | type VersionResult struct { 14 | VersionString string `json:"versionstring"` 15 | Major uint32 `json:"major"` 16 | Minor uint32 `json:"minor"` 17 | Patch uint32 `json:"patch"` 18 | Prerelease string `json:"prerelease"` 19 | BuildMetadata string `json:"buildmetadata"` 20 | } 21 | -------------------------------------------------------------------------------- /rpc/rpcserver/mocks/rpcHandler.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v1.0.0. DO NOT EDIT. 2 | 3 | package rpcserver 4 | 5 | import ( 6 | message "github.com/multivactech/MultiVAC/processor/shared/message" 7 | mock "github.com/stretchr/testify/mock" 8 | ) 9 | 10 | // rpcHandler is an autogenerated mock type for the rpcHandler type 11 | type MockRpcHandler struct { 12 | mock.Mock 13 | } 14 | 15 | // HandleRPCReq provides a mock function with given fields: req 16 | func (_m *MockRpcHandler) HandleRPCReq(req *message.RPCReq) *message.RPCResp { 17 | ret := _m.Called(req) 18 | 19 | var r0 *message.RPCResp 20 | if rf, ok := ret.Get(0).(func(*message.RPCReq) *message.RPCResp); ok { 21 | r0 = rf(req) 22 | } else { 23 | if ret.Get(0) != nil { 24 | r0 = ret.Get(0).(*message.RPCResp) 25 | } 26 | } 27 | 28 | return r0 29 | } 30 | -------------------------------------------------------------------------------- /processor/shared/message/pubsub_topics.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package message 9 | 10 | const ( 11 | // EvtSyncStart is the flag of SyncStart Event. 12 | EvtSyncStart EventTopic = iota 13 | 14 | // EvtSyncComplete is the flag of SyncComplete Event. 15 | EvtSyncComplete 16 | 17 | // EvtSyncAbort is the flag of SyncAbort Event. 18 | EvtSyncAbort 19 | 20 | // EvtLedgerFallBehind is the flag of UpdateLedger Event. 21 | // It is triggered when the consensus module detects that the round is behind. 22 | EvtLedgerFallBehind 23 | 24 | // EvtTxPoolInitFinished is the flag of TxPoolInitFinished Event. 25 | EvtTxPoolInitFinished 26 | ) 27 | -------------------------------------------------------------------------------- /processor/controller/internal/mail.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package internal 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/shard" 12 | "github.com/multivactech/MultiVAC/processor/shared/message" 13 | ) 14 | 15 | // TODO(huangsz): the concurrency concern here is only needed for handling MsgBlockConfirmation, actor doesn't seem 16 | // needed here. Actually, looks a bit strange. 17 | const ( 18 | evtAdd message.EventTopic = iota 19 | evtHandleMessage 20 | evtStartProcessor 21 | evtInit 22 | evtGetEnableShards 23 | evtGetProcessor 24 | evtGetAllProcessor 25 | ) 26 | 27 | type enableShardsResp struct { 28 | enableShards []shard.Index 29 | } 30 | -------------------------------------------------------------------------------- /processor/miner/consensus/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2013-2014 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package consensus 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger" 16 | "github.com/multivactech/MultiVAC/logger/btclog" 17 | ) 18 | 19 | var log btclog.Logger 20 | var logBackend *btclog.Backend 21 | 22 | func init() { 23 | var exists bool 24 | log, exists = logger.GetLogger(logger.ConsensusLoggerTag) 25 | if !exists { 26 | panic("Fail to get logger for consensus package") 27 | } 28 | logBackend = logger.BackendLogger() 29 | } 30 | -------------------------------------------------------------------------------- /processor/miner/consensus/mock/sync.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/configs/config" 5 | "github.com/multivactech/MultiVAC/model/wire" 6 | "github.com/multivactech/MultiVAC/p2p/connection" 7 | ) 8 | 9 | // SyncMgr is a fake struct. 10 | type SyncMgr struct{} 11 | 12 | // Start is a fake method that does nothing. 13 | func (fsm *SyncMgr) Start() {} 14 | 15 | // AcceptMsg is a fake method that does nothing. 16 | func (fsm *SyncMgr) AcceptMsg(msg wire.Message) {} 17 | 18 | // MaybeSync is a fake method that does nothing. 19 | func (fsm *SyncMgr) MaybeSync() {} 20 | 21 | // OnNewPeer is a fake method that does nothing. 22 | func (fsm *SyncMgr) OnNewPeer(cp *connection.ConnPeer, t config.NodeType) {} 23 | 24 | // OnPeerDone is a fake method that does nothing. 25 | func (fsm *SyncMgr) OnPeerDone(cp *connection.ConnPeer, t config.NodeType) {} 26 | -------------------------------------------------------------------------------- /processor/sync/synctimer_test.go: -------------------------------------------------------------------------------- 1 | package sync 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | var startTimeout = false 9 | var stopTimeout = false 10 | 11 | func TestSyncTimer_Start(t *testing.T) { 12 | syncTimer := &syncTimer{} 13 | syncTimer.start(fakeStartTimeOutFun, 2) 14 | time.Sleep(3 * time.Second) 15 | if startTimeout != true { 16 | t.Error("sync time out, but didn't call time out func") 17 | } 18 | } 19 | 20 | func fakeStartTimeOutFun() { 21 | startTimeout = true 22 | } 23 | func fakeStopTimeOutFun() { 24 | stopTimeout = true 25 | } 26 | 27 | func TestSyncTimer_Stop(t *testing.T) { 28 | syncTimer := &syncTimer{} 29 | syncTimer.start(fakeStopTimeOutFun, 2) 30 | time.Sleep(1 * time.Second) 31 | syncTimer.stop() 32 | time.Sleep(3 * time.Second) 33 | if stopTimeout == true { 34 | t.Error("syncTimer stopped, but still call time out func") 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /pos/heartbeat/mocks/mockbroadcast.go: -------------------------------------------------------------------------------- 1 | package mocks 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/model/wire" 5 | "github.com/multivactech/MultiVAC/p2p/connection" 6 | ) 7 | 8 | // MockBroadCaster is a mock broadcaster. 9 | type MockBroadCaster struct { 10 | Count int 11 | } 12 | 13 | // NewMockBroadCaster mocks a broadcaster. 14 | func NewMockBroadCaster() *MockBroadCaster { 15 | return &MockBroadCaster{Count: 0} 16 | } 17 | 18 | // BroadcastMessage mock a broadcast action. 19 | func (mbc *MockBroadCaster) BroadcastMessage(msg wire.Message, params *connection.BroadcastParams) { 20 | mbc.Count++ 21 | } 22 | 23 | // RegisterChannels is a mock method. 24 | func (mbc *MockBroadCaster) RegisterChannels(dispatch *connection.MessagesAndReceiver) { 25 | 26 | } 27 | 28 | // HandleMessage is a mock method. 29 | func (mbc *MockBroadCaster) HandleMessage(message wire.Message) { 30 | } 31 | -------------------------------------------------------------------------------- /rpc/btcjson/mtvblockinfo.go: -------------------------------------------------------------------------------- 1 | package btcjson 2 | 3 | import "github.com/multivactech/MultiVAC/model/wire" 4 | 5 | // BlockInfo contains complete blocks from the startHeight. 6 | // TODO: Maybe move this to another MTV specific package 7 | type BlockInfo struct { 8 | Block []*wire.MsgBlock 9 | StartHeight int64 10 | } 11 | 12 | // SlimBlockInfo contains the SlimBlocks from startHeight. 13 | type SlimBlockInfo struct { 14 | SlimBlock []*wire.SlimBlock 15 | Height int64 16 | } 17 | 18 | // BlockSliceInfo contains blocks from startHeight to endHeight. 19 | type BlockSliceInfo struct { 20 | Block []*wire.MsgBlock 21 | StartHeight int64 22 | EndHeight int64 23 | } 24 | 25 | // SlimBlockSliceInfo contains slimBlocks from startHeight to endHeight. 26 | type SlimBlockSliceInfo struct { 27 | SlimBlock []*wire.SlimBlock 28 | StartHeight int64 29 | EndHeight int64 30 | } 31 | -------------------------------------------------------------------------------- /processor/storagenode/depositmanager_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package storagenode 9 | 10 | import ( 11 | "testing" 12 | 13 | "github.com/multivactech/MultiVAC/model/shard" 14 | "github.com/multivactech/MultiVAC/model/wire" 15 | ) 16 | 17 | func TestRemoveOuts(t *testing.T) { 18 | shard0 := shard.IDToShardIndex(0) 19 | dm := newDepositManager() 20 | dm.removeOutsBeforeHeight(shard0, wire.BlockHeight(2)) 21 | 22 | out1 := &wire.OutState{ 23 | OutPoint: wire.OutPoint{ 24 | Shard: shard0, 25 | }, 26 | } 27 | 28 | out2 := &wire.OutState{ 29 | OutPoint: wire.OutPoint{ 30 | Shard: shard0, 31 | }, 32 | } 33 | 34 | dm.add(out1, 2) 35 | dm.add(out2, 2) 36 | dm.removeOutsBeforeHeight(shard0, 2) 37 | } 38 | -------------------------------------------------------------------------------- /interface/iconsensus/consensus.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package iconsensus 9 | 10 | // Consensus is the consensus engine 11 | type Consensus interface { 12 | // StartConsensusAtRound means set the consensus start at the round; 13 | StartConsensusAtRound(round int) 14 | // StopConsensusAtRound means when shard needs to be disabled, stop the consensus firstly 15 | StopConsensusAtRound(round int) 16 | // todo(MH): maybe remove 17 | // UpdateInShardProof will update consensusExecutor.inshardProof, it will be safe in concurrent. 18 | UpdateInShardProof(inShardProof []byte) 19 | // RegisterCEListener adds a listener to shardStateListeners 20 | RegisterCEShardStateListener(listener CEShardStateListener) 21 | 22 | Init() 23 | Start() 24 | } 25 | -------------------------------------------------------------------------------- /model/chaincfg/signature/signature_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package signature 9 | 10 | import ( 11 | "crypto/sha256" 12 | "testing" 13 | ) 14 | 15 | func TestVerifySignature(t *testing.T) { 16 | message := []byte("Heatwave: Supermarket sleepover for cool customers") 17 | randPubKeyBytes := sha256.Sum256([]byte("blahblah")) 18 | randPubKey := PublicKey(randPubKeyBytes[:]) 19 | publicKey, privateKey, err := GenerateKey(nil) 20 | if err != nil { 21 | t.Error(err.Error()) 22 | } 23 | sig := Sign(privateKey, message) 24 | 25 | if !Verify(publicKey, message, sig) { 26 | t.Error("Fail to verify message and sig") 27 | } 28 | 29 | if Verify(randPubKey, message, sig) { 30 | t.Error("Verified messaged by wrong pub key") 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /processor/miner/consensus/mock/heartbeat.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import "github.com/multivactech/MultiVAC/model/wire" 4 | 5 | // HeartBeat for easier testing. 6 | type HeartBeat struct { 7 | TestNodeNum int 8 | } 9 | 10 | // Receive implement HeartBeat interface 11 | func (thbm *HeartBeat) Receive(msg *wire.HeartBeatMsg) { 12 | 13 | } 14 | 15 | // Has implement HeartBeat interface 16 | func (thbm *HeartBeat) Has(pk []byte) bool { 17 | return true 18 | } 19 | 20 | // PerceivedCount implement HeartBeat interface 21 | func (thbm *HeartBeat) PerceivedCount() int { 22 | return thbm.TestNodeNum 23 | } 24 | 25 | // Start implement HeartBeat interface 26 | func (thbm *HeartBeat) Start() { 27 | } 28 | 29 | // Stop implement HeartBeat interface 30 | func (thbm *HeartBeat) Stop() { 31 | } 32 | 33 | // CheckConfirmation implements HeatBeat interface. 34 | func (thbm *HeartBeat) CheckConfirmation(msg *wire.MsgBlockConfirmation) bool { 35 | return true 36 | } 37 | -------------------------------------------------------------------------------- /p2p/addrmgr/internal_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Copyright (c) 2013-2015 The btcsuite developers 6 | // Use of this source code is governed by an ISC 7 | // license that can be found in the LICENSE file. 8 | 9 | package addrmgr 10 | 11 | import ( 12 | "time" 13 | 14 | "github.com/multivactech/MultiVAC/model/wire" 15 | ) 16 | 17 | func TstKnownAddressIsBad(ka *KnownAddress) bool { 18 | return ka.isBad() 19 | } 20 | 21 | func TstKnownAddressChance(ka *KnownAddress) float64 { 22 | return ka.chance() 23 | } 24 | 25 | func TstNewKnownAddress(na *wire.NetAddress, attempts int, 26 | lastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress { 27 | return &KnownAddress{na: na, attempts: attempts, lastattempt: lastattempt, 28 | lastsuccess: lastsuccess, tried: tried, refs: refs} 29 | } 30 | -------------------------------------------------------------------------------- /model/wire/smartcontract_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/interface/isysapi" 9 | "github.com/multivactech/MultiVAC/model/merkle" 10 | "github.com/multivactech/MultiVAC/model/shard" 11 | ) 12 | 13 | func newSmartContractInfoForTest() *SmartContractInfo { 14 | // TODO (wangruichao@mtv.ac): empty for now, add smart contract here 15 | sc := SmartContractInfo{ 16 | ShardIdx: shard.ShardList[0], 17 | 18 | SmartContract: &SmartContract{ 19 | ContractAddr: isysapi.SysAPIAddress, 20 | Code: []byte{}, 21 | APIList: []string{}, 22 | }, 23 | 24 | CodeOut: &OutState{}, 25 | CodeOutProof: &merkle.MerklePath{}, 26 | ShardInitOut: &OutState{}, 27 | ShardInitOutProof: &merkle.MerklePath{}, 28 | } 29 | return &sc 30 | } 31 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/util_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "net/http" 9 | "testing" 10 | ) 11 | 12 | var tokenListContainsValueTests = []struct { 13 | value string 14 | ok bool 15 | }{ 16 | {"WebSocket", true}, 17 | {"WEBSOCKET", true}, 18 | {"websocket", true}, 19 | {"websockets", false}, 20 | {"x websocket", false}, 21 | {"websocket x", false}, 22 | {"other,websocket,more", true}, 23 | {"other, websocket, more", true}, 24 | } 25 | 26 | func TestTokenListContainsValue(t *testing.T) { 27 | for _, tt := range tokenListContainsValueTests { 28 | h := http.Header{"Upgrade": {tt.value}} 29 | ok := tokenListContainsValue(h, "Upgrade", "websocket") 30 | if ok != tt.ok { 31 | t.Errorf("tokenListContainsValue(h, n, %q) = %v, want %v", tt.value, ok, tt.ok) 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /rpc/rpcclient/examples/bitcoincorehttp/README.md: -------------------------------------------------------------------------------- 1 | Bitcoin Core HTTP POST Example 2 | ============================== 3 | 4 | This example shows how to use the rpcclient package to connect to a Bitcoin 5 | Core RPC server using HTTP POST mode with TLS disabled and gets the current 6 | block count. 7 | 8 | ## Running the Example 9 | 10 | The first step is to use `go get` to download and install the rpcclient package: 11 | 12 | ```bash 13 | $ go get github.com/multivactech/MultiVAC/rpcclient 14 | ``` 15 | 16 | Next, modify the `main.go` source to specify the correct RPC username and 17 | password for the RPC server: 18 | 19 | ```Go 20 | User: "yourrpcuser", 21 | Pass: "yourrpcpass", 22 | ``` 23 | 24 | Finally, navigate to the example's directory and run it with: 25 | 26 | ```bash 27 | $ cd $GOPATH/src/github.com/multivactech/MultiVAC/rpcclient/examples/bitcoincorehttp 28 | $ go run *.go 29 | ``` 30 | 31 | ## License 32 | 33 | This example is licensed under the [copyfree](http://copyfree.org) ISC License. 34 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/server_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "net/http" 9 | "reflect" 10 | "testing" 11 | ) 12 | 13 | var subprotocolTests = []struct { 14 | h string 15 | protocols []string 16 | }{ 17 | {"", nil}, 18 | {"foo", []string{"foo"}}, 19 | {"foo,bar", []string{"foo", "bar"}}, 20 | {"foo, bar", []string{"foo", "bar"}}, 21 | {" foo, bar", []string{"foo", "bar"}}, 22 | {" foo, bar ", []string{"foo", "bar"}}, 23 | } 24 | 25 | func TestSubprotocols(t *testing.T) { 26 | for _, st := range subprotocolTests { 27 | r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} 28 | protocols := Subprotocols(&r) 29 | if !reflect.DeepEqual(st.protocols, protocols) { 30 | t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /mvvm/deploymvvm_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package mvvm 9 | 10 | import ( 11 | "fmt" 12 | "io/ioutil" 13 | "testing" 14 | 15 | "github.com/multivactech/MultiVAC/model/shard" 16 | ) 17 | 18 | func getTestCode(filename string) []byte { 19 | bytes, err := ioutil.ReadFile(filename) 20 | if err != nil { 21 | panic(err) 22 | } 23 | return bytes 24 | } 25 | 26 | func TestNewDeployMvvm(t *testing.T) { 27 | code := getTestCode("test_init.wasm") 28 | vm, err := NewDeployMvvm(code) 29 | if err != nil { 30 | t.Error(err) 31 | } 32 | defer func() { 33 | if r := recover(); r != nil { 34 | t.Error("runtime error when executing init") 35 | } 36 | }() 37 | data := vm.Initialize(shard.Index(0)) 38 | if string(data) != "abcdefghijklmnopqrstuvwxyz" { 39 | t.Error(fmt.Errorf("incorrect return value: %v", data)) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /interface/icontroller/shardcontroller.go: -------------------------------------------------------------------------------- 1 | package icontroller 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/configs/config" 5 | "github.com/multivactech/MultiVAC/model/shard" 6 | "github.com/multivactech/MultiVAC/p2p/connection" 7 | "github.com/multivactech/MultiVAC/processor/shared/message" 8 | ) 9 | 10 | // IShardController defines the local interface which serves as the entry for business logic in a particular shard. 11 | type IShardController interface { 12 | // NotifyNewPeerAdded sends new peer added information to mtvSyncMgr 13 | NotifyNewPeerAdded(cp *connection.ConnPeer, t config.NodeType) 14 | // NotifyPeerDone sends the new-done information to syncManager. 15 | NotifyPeerDone(cp *connection.ConnPeer, t config.NodeType) 16 | // HandleRPCReq handles a RPCReq for the relevant shard. 17 | HandleRPCReq(req *message.RPCReq) *message.RPCResp 18 | // ShardIndex returns the index of the shardController 19 | ShardIndex() shard.Index 20 | // IsEnabled returns if the processor is in working. 21 | IsEnabled() bool 22 | } 23 | -------------------------------------------------------------------------------- /model/chaincfg/chainhash/hashfuncs.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The Decred developers 2 | // Copyright (c) 2016-2017 The btcsuite developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package chainhash 7 | 8 | import "crypto/sha256" 9 | 10 | // HashB calculates hash(b) and returns the resulting bytes. 11 | func HashB(b []byte) []byte { 12 | hash := sha256.Sum256(b) 13 | return hash[:] 14 | } 15 | 16 | // HashH calculates hash(b) and returns the resulting bytes as a Hash. 17 | func HashH(b []byte) Hash { 18 | return Hash(sha256.Sum256(b)) 19 | } 20 | 21 | // DoubleHashB calculates hash(hash(b)) and returns the resulting bytes. 22 | func DoubleHashB(b []byte) []byte { 23 | first := sha256.Sum256(b) 24 | second := sha256.Sum256(first[:]) 25 | return second[:] 26 | } 27 | 28 | // DoubleHashH calculates hash(hash(b)) and returns the resulting bytes as a 29 | // Hash. 30 | func DoubleHashH(b []byte) Hash { 31 | first := sha256.Sum256(b) 32 | return Hash(sha256.Sum256(first[:])) 33 | } 34 | -------------------------------------------------------------------------------- /model/wire/msgstartnet.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/base/rlp" 11 | ) 12 | 13 | // MsgStartNet ??? 14 | type MsgStartNet struct { 15 | } 16 | 17 | // BtcDecode decode the message. 18 | func (m *MsgStartNet) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 19 | return rlp.Decode(r, m) 20 | } 21 | 22 | // BtcEncode encode the message. 23 | func (m *MsgStartNet) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 24 | return rlp.Encode(w, m) 25 | } 26 | 27 | // Command returns the command string. 28 | func (m *MsgStartNet) Command() string { 29 | return CmdStartNet 30 | } 31 | 32 | // MaxPayloadLength return the mac playload length of MsgStartNet. 33 | func (m *MsgStartNet) MaxPayloadLength(uint32) uint32 { 34 | // TODO Change it to a proper value. 35 | return LargeMaxPayloadLength 36 | } 37 | -------------------------------------------------------------------------------- /interface/imvvm/mvvm.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package imvvm 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/shard" 9 | "github.com/multivactech/MultiVAC/model/wire" 10 | ) 11 | 12 | // DeployInitializer will initialize the initial data of each shard when a smart contract is deployed. 13 | type DeployInitializer interface { 14 | // Initialize is called when a smart contract is deployed and initialized. 15 | Initialize(shard shard.Index) []byte 16 | } 17 | 18 | // SmartContractMvvmExecutor will execute the given code when the smart contract is applied, and return a bunch of 19 | // OutState and Action to change the status of each shard. 20 | type SmartContractMvvmExecutor interface { 21 | // Execute is called when a smart contract is applied and executed. 22 | Execute(tx *wire.MsgTx, shardState *wire.OutState) (*wire.OutState, []*wire.OutState, []*wire.ReduceAction, error) 23 | } 24 | -------------------------------------------------------------------------------- /configs/config/config_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package config 9 | 10 | import "testing" 11 | 12 | func fakeConfig(storageNode bool) *Config { 13 | return &Config{StorageNode: storageNode} 14 | } 15 | 16 | func TestGetNodeType(t *testing.T) { 17 | tests := []struct { 18 | desc string 19 | storageNode bool 20 | expectedNodeType NodeType 21 | }{ 22 | { 23 | desc: "Storage node", 24 | storageNode: true, 25 | expectedNodeType: StorageNode, 26 | }, 27 | { 28 | desc: "Miner node", 29 | storageNode: false, 30 | expectedNodeType: MinerNode, 31 | }, 32 | } 33 | for _, test := range tests { 34 | globalCfg = fakeConfig(test.storageNode) 35 | if tt := GetNodeType(); tt != test.expectedNodeType { 36 | t.Errorf("Running test %v failed, expected: %v, get: %v", test.desc, test.expectedNodeType, tt) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /processor/miner/consensus/mock/bcproducer.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/model/shard" 5 | "github.com/multivactech/MultiVAC/model/wire" 6 | ) 7 | 8 | // BcProducer for easier testing. 9 | type BcProducer struct { 10 | shard shard.Index 11 | blockHeader *wire.BlockHeader 12 | } 13 | 14 | // NewMockBcProducer return BcProducer. 15 | func NewMockBcProducer(shard shard.Index) *BcProducer { 16 | return &BcProducer{shard: shard} 17 | } 18 | 19 | // GenerateBlockConfirmation generate blockconfirmation message by bba final message. 20 | func (mbcp *BcProducer) GenerateBlockConfirmation(message *wire.MsgBinaryBAFin) *wire.MsgBlockConfirmation { 21 | v := message.GetByzAgreementValue() 22 | return wire.NewMessageBlockConfirmation( 23 | mbcp.shard, 24 | int32(message.GetRound()), 25 | int32(message.GetStep()), 26 | &v, 27 | mbcp.blockHeader, 28 | []*wire.MsgBinaryBAFin{message}, 29 | ) 30 | } 31 | 32 | // SaveHeader cache block header. 33 | func (mbcp *BcProducer) SaveHeader(header *wire.BlockHeader) { 34 | mbcp.blockHeader = header 35 | } 36 | -------------------------------------------------------------------------------- /processor/miner/consensus/sortition_test.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | 7 | "github.com/multivactech/MultiVAC/model/shard" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | var ( 12 | testNumShard uint32 = 4 13 | testLeaderRate uint32 = 4 14 | // IsLeader is always equal to true when leaderRates is equal to one. 15 | testLeaderRateIsOne = 1 16 | testShard = shard.Index(0) 17 | testLeaderSeed, _ = hex.DecodeString("205f642c8390293eb74d08cf38d3333771e9e319cfd12a21429eeff2eddeebd2") 18 | testNotLeaderSeed, _ = hex.DecodeString("885f642c8390293eb74d08cf38d3333771e9e319cfd12a21429eeff2eddeebd2") 19 | ) 20 | 21 | func TestSortitionor_IsLeader(t *testing.T) { 22 | // init new Sortitionor 23 | ds := NewSortitionor(testNumShard, testLeaderRate) 24 | 25 | assert.Equal(t, ds.IsLeader(testLeaderSeed, testShard), true) 26 | assert.Equal(t, ds.IsLeader(testNotLeaderSeed, testShard), false) 27 | 28 | ds.SetLeaderRate(testLeaderRateIsOne, testShard) 29 | assert.Equal(t, ds.IsLeader(testNotLeaderSeed, testShard), true) 30 | } 31 | -------------------------------------------------------------------------------- /model/chaincfg/params_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package chaincfg 6 | 7 | import "testing" 8 | 9 | // TestInvalidHashStr ensures the newShaHashFromStr function panics when used to 10 | // with an invalid hash string. 11 | func TestInvalidHashStr(t *testing.T) { 12 | defer func() { 13 | if r := recover(); r == nil { 14 | t.Errorf("Expected panic for invalid hash, got nil") 15 | } 16 | }() 17 | newHashFromStr("banana") 18 | } 19 | 20 | // TestMustRegisterPanic ensures the mustRegister function panics when used to 21 | // register an invalid network. 22 | func TestMustRegisterPanic(t *testing.T) { 23 | t.Parallel() 24 | 25 | // Setup a defer to catch the expected panic to ensure it actually 26 | // paniced. 27 | defer func() { 28 | if err := recover(); err == nil { 29 | t.Error("mustRegister did not panic as expected") 30 | } 31 | }() 32 | 33 | // Intentionally try to register duplicate params to force a panic. 34 | mustRegister(&MainNetParams) 35 | } 36 | -------------------------------------------------------------------------------- /interface/idepositpool/depositpool.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package idepositpool 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 9 | "github.com/multivactech/MultiVAC/model/merkle" 10 | "github.com/multivactech/MultiVAC/model/shard" 11 | "github.com/multivactech/MultiVAC/model/wire" 12 | "github.com/multivactech/MultiVAC/processor/shared/state" 13 | ) 14 | 15 | // DepositPool used to manage deposit outs. 16 | type DepositPool interface { 17 | Add(out *wire.OutPoint, height wire.BlockHeight, proof *merkle.MerklePath) error 18 | Remove(out *wire.OutPoint) error 19 | Update(update *state.Update, shard shard.Index, height wire.BlockHeight) error 20 | GetBiggest(address multivacaddress.Address) ([]byte, error) 21 | GetAll(shard shard.Index, address multivacaddress.Address) ([]*wire.OutWithProof, error) 22 | Verify(address multivacaddress.Address, proof []byte) bool 23 | Lock(out *wire.OutPoint) error 24 | } 25 | -------------------------------------------------------------------------------- /rpc/btcjson/mtvshardinfo.go: -------------------------------------------------------------------------------- 1 | package btcjson 2 | 3 | import "github.com/multivactech/MultiVAC/model/shard" 4 | 5 | // ShardInfo defines a struct that contains a shard index and its state. 6 | // TODO Maybe move this to another MTV specific package 7 | type ShardInfo struct { 8 | Index shard.Index 9 | Enabled bool 10 | } 11 | 12 | // ShardsInfo contains the a list of shard, it is used as the response of queryshardinfo rpc. 13 | type ShardsInfo struct { 14 | NumShards int 15 | Shards []ShardInfo 16 | } 17 | 18 | // Len is the number of elements in the collection. Implements sort.Interface 19 | func (s *ShardsInfo) Len() int { 20 | return s.NumShards 21 | } 22 | 23 | // Less reports whether the element with 24 | // index i should sort before the element with index j. Implements sort.Interface 25 | func (s *ShardsInfo) Less(i, j int) bool { 26 | return s.Shards[i].Index.GetID() < s.Shards[j].Index.GetID() 27 | } 28 | 29 | // Swap swaps the elements with indexes i and j. Implements sort.Interface 30 | func (s *ShardsInfo) Swap(i, j int) { 31 | tmp := s.Shards[i] 32 | s.Shards[i] = s.Shards[j] 33 | s.Shards[j] = tmp 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018-present, MultiVAC dev team 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /logger/btclog/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package btclog defines an interface and default implementation for subsystem 6 | // logging. 7 | // 8 | // Log level verbosity may be modified at runtime for each individual subsystem 9 | // logger. 10 | // 11 | // The default implementation in this package must be created by the Backend type. 12 | // Backends can write to any io.Writer, including multi-writers created by 13 | // io.MultiWriter. Multi-writers allow log output to be written to many writers, 14 | // including standard output and log files. 15 | // 16 | // Optional logging behavior can be specified by using the LOGFLAGS environment 17 | // variable and overridden per-Backend by using the WithFlags call option. Multiple 18 | // LOGFLAGS options can be specified, separated by commas. The following options 19 | // are recognized: 20 | // longfile: Include the full filepath and line number in all log message 21 | // shortfile: Include the filename and line number in all log messages. 22 | // Overrides longfile. 23 | package btclog 24 | -------------------------------------------------------------------------------- /processor/shared/txpool/interface.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package txpool 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/merkle" 12 | "github.com/multivactech/MultiVAC/model/wire" 13 | "github.com/multivactech/MultiVAC/processor/shared/state" 14 | ) 15 | 16 | // TxPool is a interface that contains some methods used to add, verify and get transactions with proofs. 17 | type TxPool interface { 18 | AddNewTransaction(tx *wire.MsgTxWithProofs, root *merkle.MerkleHash) (*TxDesc, error) 19 | VerifyTransaction(tx *wire.MsgTxWithProofs, root *merkle.MerkleHash) error 20 | GetTopTransactions(number int, update *state.Update, height int64) []*wire.MsgTxWithProofs 21 | NumberOfTransactions() int 22 | RefreshPool(update *state.Update) 23 | } 24 | 25 | // NewTxPool returns a new instance of txPool. 26 | func NewTxPool() TxPool { 27 | return &txPool{ 28 | pool: make(map[merkle.MerkleHash]*TxDesc), 29 | usedOutsInPool: make(map[merkle.MerkleHash]bool), 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /base/util/shard.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package util 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "fmt" 11 | "os/exec" 12 | ) 13 | 14 | // Int64ToBytes transform int64 to byte array. 15 | func Int64ToBytes(i int64) []byte { 16 | var buf = make([]byte, 8) 17 | binary.BigEndian.PutUint64(buf, uint64(i)) 18 | return buf 19 | } 20 | 21 | // BytesToInt64 transform the byte array to int64. 22 | func BytesToInt64(buf []byte) int64 { 23 | if len(buf) < 1 { 24 | return 0 25 | } 26 | return int64(binary.BigEndian.Uint64(buf)) 27 | } 28 | 29 | func RedirectLog(content, fileAbsPath string) (string, error) { 30 | str := fmt.Sprintf("echo \"%s\">>%s", content, fileAbsPath) 31 | cmd := exec.Command("sh", "-c", str) 32 | 33 | var out bytes.Buffer 34 | var stderr bytes.Buffer 35 | cmd.Stdout = &out 36 | cmd.Stderr = &stderr 37 | 38 | err := cmd.Run() 39 | if err != nil && stderr.String() != "" { 40 | return "", fmt.Errorf("err: %v %v", err, stderr.String()) 41 | } 42 | 43 | return out.String(), nil 44 | } 45 | -------------------------------------------------------------------------------- /processor/sync/synctimer.go: -------------------------------------------------------------------------------- 1 | package sync 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | // syncTimer is a timer for sync, the timer will start when start to sync. 8 | // If sync isn't completed within a certain period, the timeour func will be triggered. 9 | type syncTimer struct { 10 | ticker *time.Ticker 11 | isStop chan bool 12 | } 13 | 14 | // syncTimer start, onTimeOut is the timeout func. 15 | func (st *syncTimer) start(onTimeOut timerCallback, timeOutInSec int) { 16 | st.ticker = time.NewTicker(time.Duration(timeOutInSec) * time.Second) 17 | if st.isStop == nil { 18 | st.isStop = make(chan bool, 1) 19 | } 20 | go st.timeoutRoutine(onTimeOut) 21 | } 22 | 23 | // syncTimer stop. 24 | func (st *syncTimer) stop() { 25 | st.stopTicker() 26 | } 27 | 28 | func (st *syncTimer) stopTicker() { 29 | if st.ticker != nil { 30 | st.ticker.Stop() 31 | } 32 | if st.isStop != nil { 33 | st.isStop <- true 34 | } 35 | } 36 | func (st *syncTimer) timeoutRoutine(onTimeOut func()) { 37 | for { 38 | select { 39 | case <-st.ticker.C: 40 | log.Errorf("Sync time out!") 41 | onTimeOut() 42 | st.stopTicker() 43 | case <-st.isStop: 44 | return 45 | } 46 | } 47 | } 48 | 49 | type timerCallback func() 50 | -------------------------------------------------------------------------------- /install: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | """ 4 | Script for installing multivac, including auto-gen necessary code. 5 | """ 6 | 7 | import os 8 | import subprocess 9 | 10 | def execute(cmds, realtime_output=False): 11 | p = subprocess.Popen(cmds, stdout=subprocess.PIPE) 12 | if realtime_output: 13 | while p.poll() is None: 14 | l = p.stdout.readline() # This blocks until it receives a newline. 15 | print l 16 | print p.stdout.read() 17 | else: 18 | return p.communicate() 19 | 20 | def gen_code(): 21 | print "Generating code..." 22 | go_pkgs = execute(["go", "list", "-f", "{{.Dir}}", "./..."])[0].split() 23 | for p in go_pkgs: 24 | os.chdir(p) 25 | subprocess.check_call(["go", "generate"]) 26 | 27 | def wire_download(): 28 | subprocess.call("go get github.com/google/wire/cmd/wire", shell=True) 29 | 30 | 31 | if __name__ == "__main__": 32 | wire_download() 33 | root_path = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir)) 34 | os.chdir(root_path) 35 | gen_code() 36 | print "Installing..." 37 | os.chdir(root_path) 38 | subprocess.check_call(["go", "install"]) 39 | print 'Complete' 40 | -------------------------------------------------------------------------------- /model/chaincfg/genesis/shard.go.template: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | /** 9 | * This package keeps the parameters of the protocol which are use by many packages. 10 | * 11 | * The difference from this package to package `config` is that this package should 12 | * be determined by compile time. For runtime config which users should be able to set 13 | * via command line flag, please use `config` package. 14 | * To avoid dependency loop, this package should dependes on no other packages 15 | * in this repo. 16 | */ 17 | package params 18 | 19 | // This is file is generated by chaincfg/genesis/script.py 20 | // Please not edit manually, otherwise the change might get 21 | // override. 22 | 23 | 24 | const ( 25 | // Defines the length of prefix, this is used to generate shard list and genesis blocks. 26 | // e.g. When the prefix is 4, there are 2^4 = 16 shards. 27 | // Note: The max value for this prefix length is 32. 28 | GenesisShardPrefixLength = %(prefix_length)s 29 | GenesisNumberOfShards = 1 << GenesisShardPrefixLength 30 | ) 31 | -------------------------------------------------------------------------------- /monitoring/multivac.rules.yaml: -------------------------------------------------------------------------------- 1 | groups: 2 | - name: multivac monitoring 3 | rules: 4 | - record: shard:multivac_shard_size 5 | expr: sum(multivac_shard_presence) by (shard_id) 6 | 7 | - record: shard:multivac_tps 8 | expr: avg(rate(multivac_confirmed_tx_cnt[1m])) by (shard_id) 9 | 10 | - record: shard:multivac_pending_tx 11 | expr: avg(multivac_pending_tx_cnt) by (shard_id) 12 | 13 | - record: shard:multivac_broadcast_msg_rate 14 | expr: sum(rate(multivac_broadcasted_msg_cnt[1m])) by (shard_id) 15 | 16 | - record: shard:multivac_shard_max_height 17 | expr: max(multivac_shard_height) by (shard_id) 18 | 19 | - record: shard:multivac_shard_enabled_miner 20 | expr: sum(multivac_shard_enabled_miner_num) by (shard_id) 21 | 22 | # TODO Make a distribution for cpu usage perhaps, do not calculate 3 times. 23 | - record: global:min_cpu_usage 24 | expr: min(rate(node_cpu_seconds_total{mode="user"}[1m])) 25 | 26 | - record: global:max_cpu_usage 27 | expr: max(rate(node_cpu_seconds_total{mode="user"}[1m])) 28 | 29 | - record: global:avg_cpu_usage 30 | expr: avg(rate(node_cpu_seconds_total{mode="user"}[1m])) 31 | -------------------------------------------------------------------------------- /configs/params/shard.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Package params : 6 | // This package keeps the parameters of the protocol which are use by many packages. 7 | // The difference from this package to package `config` is that this package should 8 | // be determined by compile time. For runtime config which users should be able to set 9 | // via command line flag, please use `config` package. 10 | // To avoid dependency loop, this package should depend on no other packages 11 | // in this repo. 12 | package params 13 | 14 | // This is file is generated by chaincfg/genesis/script.py 15 | // Please not edit manually, otherwise the change might get 16 | // override. 17 | 18 | const ( 19 | // GenesisShardPrefixLength defines the length of prefix, this is used to generate shard list and genesis blocks. 20 | // e.g. When the prefix is 4, there are 2^4 = 16 shards. 21 | // Note: The max value for this prefix length is 32. 22 | GenesisShardPrefixLength = 2 23 | // GenesisNumberOfShards defines the number of miner in shard. 24 | GenesisNumberOfShards = 1 << GenesisShardPrefixLength 25 | ) 26 | -------------------------------------------------------------------------------- /processor/controller/mocks/iReshardHandler.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v1.0.0. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | shard "github.com/multivactech/MultiVAC/model/shard" 7 | mock "github.com/stretchr/testify/mock" 8 | 9 | wire "github.com/multivactech/MultiVAC/model/wire" 10 | ) 11 | 12 | // MockedReshardHandler is an autogenerated mock type for the MockedReshardHandler type 13 | type MockedReshardHandler struct { 14 | mock.Mock 15 | } 16 | 17 | // GetEnableShards provides a mock function with given fields: 18 | func (_m *MockedReshardHandler) GetEnableShards() []shard.Index { 19 | ret := _m.Called() 20 | 21 | var r0 []shard.Index 22 | if rf, ok := ret.Get(0).(func() []shard.Index); ok { 23 | r0 = rf() 24 | } else { 25 | if ret.Get(0) != nil { 26 | r0 = ret.Get(0).([]shard.Index) 27 | } 28 | } 29 | 30 | return r0 31 | } 32 | 33 | // HandleConfirmationMessage provides a mock function with given fields: msg 34 | func (_m *MockedReshardHandler) HandleConfirmationMessage(msg *wire.MsgBlockConfirmation) { 35 | _m.Called(msg) 36 | } 37 | 38 | // StartEnabledShardControllers provides a mock function with given fields: 39 | func (_m *MockedReshardHandler) StartEnabledShardControllers() { 40 | _m.Called() 41 | } 42 | -------------------------------------------------------------------------------- /model/wire/error.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | // MessageError describes an issue with a message. 12 | // An example of some potential issues are messages from the wrong bitcoin 13 | // network, invalid commands, mismatched checksums, and exceeding max payloads. 14 | // 15 | // This provides a mechanism for the caller to type assert the error to 16 | // differentiate between general io errors such as io.EOF and issues that 17 | // resulted from malformed messages. 18 | type MessageError struct { 19 | Func string // Function name 20 | Description string // Human readable description of the issue 21 | } 22 | 23 | // Error satisfies the error interface and prints human-readable errors. 24 | func (e *MessageError) Error() string { 25 | if e.Func != "" { 26 | return fmt.Sprintf("%v: %v", e.Func, e.Description) 27 | } 28 | return e.Description 29 | } 30 | 31 | // messageError creates an error for the given function and description. 32 | func messageError(f string, desc string) *MessageError { 33 | return &MessageError{Func: f, Description: desc} 34 | } 35 | -------------------------------------------------------------------------------- /processor/controller/shardproxies.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // This file defines the relevant interfaces and logic that proxies routing and dispatching work to shards. 9 | 10 | package controller 11 | 12 | import ( 13 | "github.com/multivactech/MultiVAC/interface/icontroller" 14 | "github.com/multivactech/MultiVAC/model/shard" 15 | ) 16 | 17 | // iReshardHandler defines the local interface for handling re-sharding relevant logic. 18 | type iReshardHandler interface { 19 | // StartEnabledShardControllers triggers the start of all enabled shards controllers. 20 | StartEnabledShardControllers() 21 | // GetEnableShards returns the enabled shard index array. 22 | GetEnableShards() []shard.Index 23 | } 24 | 25 | // iShardRouter defines the local instance for routing the shards. 26 | type iShardRouter interface { 27 | // GetShardController returns the shard controller for given shard 28 | GetShardController(shardIndex shard.Index) icontroller.IShardController 29 | // GetAllShardControllers returns all shard controllers 30 | GetAllShardControllers() []icontroller.IShardController 31 | } 32 | -------------------------------------------------------------------------------- /configs/limits/limits_unix.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !windows,!plan9 6 | 7 | package limits 8 | 9 | import ( 10 | "fmt" 11 | "syscall" 12 | ) 13 | 14 | const ( 15 | fileLimitWant = 2048 16 | fileLimitMin = 1024 17 | ) 18 | 19 | // SetLimits raises some process limits to values which allow btcd and 20 | // associated utilities to run. 21 | func SetLimits() error { 22 | var rLimit syscall.Rlimit 23 | 24 | err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) 25 | if err != nil { 26 | return err 27 | } 28 | if rLimit.Cur > fileLimitWant { 29 | return nil 30 | } 31 | if rLimit.Max < fileLimitMin { 32 | err = fmt.Errorf("need at least %v file descriptors", 33 | fileLimitMin) 34 | return err 35 | } 36 | if rLimit.Max < fileLimitWant { 37 | rLimit.Cur = rLimit.Max 38 | } else { 39 | rLimit.Cur = fileLimitWant 40 | } 41 | err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) 42 | if err != nil { 43 | // try min value 44 | rLimit.Cur = fileLimitMin 45 | err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) 46 | if err != nil { 47 | return err 48 | } 49 | } 50 | 51 | return nil 52 | } 53 | -------------------------------------------------------------------------------- /model/wire/msg_resendsyncreq.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "io" 5 | 6 | "github.com/multivactech/MultiVAC/base/rlp" 7 | ) 8 | 9 | const ( 10 | // MsgReSendSyncReqMaxPayload is a very arbitrary number 11 | MsgReSendSyncReqMaxPayload = 4000000 12 | ) 13 | 14 | // MsgReSendSyncReq 用于同步过程中重新发送同步请求 15 | type MsgReSendSyncReq struct { 16 | } 17 | 18 | // NewReSendSyncReq create a resend sync request message. 19 | func NewReSendSyncReq() *MsgReSendSyncReq { 20 | msg := MsgReSendSyncReq{} 21 | return &msg 22 | } 23 | 24 | // BtcDecode decode the message. 25 | func (msg *MsgReSendSyncReq) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 26 | return rlp.Decode(r, msg) 27 | } 28 | 29 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 30 | func (msg *MsgReSendSyncReq) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 31 | return rlp.Encode(w, msg) 32 | } 33 | 34 | // Command returns the protocol command string for the message. 35 | func (msg *MsgReSendSyncReq) Command() string { 36 | return CmdReSendSyncreq 37 | } 38 | 39 | // MaxPayloadLength returns the maximum length the payload can be for the 40 | // receiver. 41 | func (msg *MsgReSendSyncReq) MaxPayloadLength(uint32) uint32 { 42 | return MsgReSendSyncReqMaxPayload 43 | } 44 | -------------------------------------------------------------------------------- /interface/isync/syncmanager.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Package isync defines the interface of sync 6 | package isync 7 | 8 | import ( 9 | "github.com/multivactech/MultiVAC/configs/config" 10 | "github.com/multivactech/MultiVAC/model/wire" 11 | "github.com/multivactech/MultiVAC/p2p/connection" 12 | ) 13 | 14 | const ( 15 | // MaxSyncHeadersPerMsg is the max number of message that a peer chould sync 16 | MaxSyncHeadersPerMsg = 10 17 | ) 18 | 19 | // SyncManager used to sync header or block from peer 20 | type SyncManager interface { 21 | // Start will start the processing of sync management. 22 | Start() 23 | 24 | // AcceptMsg accepts a new message and maybe act on it. 25 | AcceptMsg(msg wire.Message) 26 | 27 | // Notifies SyncManager to request a sync, whether or not a sync will actually happen depending on internal logic. 28 | MaybeSync() 29 | 30 | // TODO(huangsz): Remove these peer relevant interfaces when p2p refactor is done, we shall register a listener 31 | // to PeerManager instead. 32 | OnNewPeer(cp *connection.ConnPeer, t config.NodeType) 33 | OnPeerDone(cp *connection.ConnPeer, t config.NodeType) 34 | } 35 | -------------------------------------------------------------------------------- /base/go-socks/socks/conn.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Samuel Stauffer. All rights reserved. 2 | // Use of this source code is governed by a 3-clause BSD 3 | // license that can be found in the LICENSE file. 4 | 5 | package socks 6 | 7 | import ( 8 | "net" 9 | "time" 10 | ) 11 | 12 | type proxiedConn struct { 13 | conn net.Conn 14 | remoteAddr *ProxiedAddr 15 | boundAddr *ProxiedAddr 16 | } 17 | 18 | func (c *proxiedConn) Read(b []byte) (int, error) { 19 | return c.conn.Read(b) 20 | } 21 | 22 | func (c *proxiedConn) Write(b []byte) (int, error) { 23 | return c.conn.Write(b) 24 | } 25 | 26 | func (c *proxiedConn) Close() error { 27 | return c.conn.Close() 28 | } 29 | 30 | func (c *proxiedConn) LocalAddr() net.Addr { 31 | if c.boundAddr != nil { 32 | return c.boundAddr 33 | } 34 | return c.conn.LocalAddr() 35 | } 36 | 37 | func (c *proxiedConn) RemoteAddr() net.Addr { 38 | if c.remoteAddr != nil { 39 | return c.remoteAddr 40 | } 41 | return c.conn.RemoteAddr() 42 | } 43 | 44 | func (c *proxiedConn) SetDeadline(t time.Time) error { 45 | return c.conn.SetDeadline(t) 46 | } 47 | 48 | func (c *proxiedConn) SetReadDeadline(t time.Time) error { 49 | return c.conn.SetReadDeadline(t) 50 | } 51 | 52 | func (c *proxiedConn) SetWriteDeadline(t time.Time) error { 53 | return c.conn.SetWriteDeadline(t) 54 | } 55 | -------------------------------------------------------------------------------- /server/autoupdater/poller.go: -------------------------------------------------------------------------------- 1 | package autoupdater 2 | 3 | import ( 4 | "bytes" 5 | "log" 6 | "net/url" 7 | "time" 8 | ) 9 | 10 | // poller polls the given URL periodically and sends messages 11 | // to the `changes` channel when the content of the URL changes. 12 | type poller struct { 13 | url url.URL 14 | interval time.Duration 15 | ticker *time.Ticker 16 | changes chan []byte 17 | quit chan struct{} 18 | 19 | lastResult []byte 20 | } 21 | 22 | func newPoller(url url.URL, interval time.Duration) *poller { 23 | return &poller{ 24 | url: url, 25 | interval: interval, 26 | changes: make(chan []byte), 27 | quit: make(chan struct{}), 28 | } 29 | } 30 | 31 | func (p *poller) Start() { 32 | if p.ticker != nil { 33 | p.ticker.Stop() 34 | } 35 | p.ticker = time.NewTicker(p.interval) 36 | go func() { 37 | for { 38 | select { 39 | case <-p.ticker.C: 40 | p.Poll() 41 | case <-p.quit: 42 | return 43 | } 44 | } 45 | }() 46 | } 47 | 48 | func (p *poller) Poll() { 49 | res, err := download(p.url.String()) 50 | if err != nil { 51 | log.Println(err) 52 | return 53 | } 54 | if !bytes.Equal(res, p.lastResult) { 55 | p.changes <- res 56 | p.lastResult = res 57 | } 58 | } 59 | 60 | func (p *poller) Stop() { 61 | p.quit <- struct{}{} 62 | p.ticker.Stop() 63 | } 64 | -------------------------------------------------------------------------------- /processor/shared/smartcontractdatastore/interface.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package smartcontractdatastore 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 12 | "github.com/multivactech/MultiVAC/model/merkle" 13 | "github.com/multivactech/MultiVAC/model/shard" 14 | "github.com/multivactech/MultiVAC/model/wire" 15 | "github.com/multivactech/MultiVAC/processor/shared/state" 16 | ) 17 | 18 | // SmartContractDataStore is a interface that contains some methods used for getting or updating the smart contract. 19 | type SmartContractDataStore interface { 20 | AddSmartContractInfo(scInfo *wire.SmartContractInfo, root *merkle.MerkleHash) error 21 | GetSmartContractInfo(addr multivacaddress.PublicKeyHash) *wire.SmartContractInfo 22 | RefreshDataStore(update *state.Update, actions []*wire.UpdateAction) 23 | Reset() 24 | } 25 | 26 | // NewSmartContractDataStore returns a new instance of smartContractDataStore. 27 | func NewSmartContractDataStore(shardIdx shard.Index) *SContractDataStore { 28 | return &SContractDataStore{ 29 | shardIdx: shardIdx, 30 | dataStore: make(map[multivacaddress.PublicKeyHash]*wire.SmartContractInfo), 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /processor/storagenode/injector.go: -------------------------------------------------------------------------------- 1 | // +build wireinject 2 | // The build tag makes sure the stub is not built in the final build. 3 | 4 | package storagenode 5 | 6 | import ( 7 | "fmt" 8 | "github.com/multivactech/MultiVAC/interface/iheartbeat" 9 | 10 | di "github.com/google/wire" 11 | "github.com/multivactech/MultiVAC/interface/iblockchain" 12 | "github.com/multivactech/MultiVAC/interface/idepositpool" 13 | "github.com/multivactech/MultiVAC/logger" 14 | "github.com/multivactech/MultiVAC/logger/btclog" 15 | "github.com/multivactech/MultiVAC/model/shard" 16 | ) 17 | 18 | // StorageDir is defined as string type 19 | type StorageDir string 20 | 21 | // NewStorageProcessor returns a new instance of StorageProcessor. 22 | func NewStorageProcessor(shard2 shard.Index, dataDir StorageDir, blockChain iblockchain.BlockChain, 23 | dPool idepositpool.DepositPool, heartBeatManager iheartbeat.HeartBeat) *Processor { 24 | panic(di.Build(di.NewSet( 25 | provideProcessor, 26 | newStorageNode, 27 | newThreadedStorageNode, 28 | provideLogger, 29 | ))) 30 | } 31 | 32 | func provideProcessor(logger btclog.Logger, sn *threadedStorageNode) *Processor { 33 | return &Processor{sn: sn, logger: logger} 34 | } 35 | 36 | func provideLogger(shard shard.Index) btclog.Logger { 37 | return logBackend.Logger( 38 | fmt.Sprintf("%s-%d", logger.StorageLoggerTag, shard.GetID())) 39 | } 40 | -------------------------------------------------------------------------------- /rpc/rpcclient/examples/bitcoincorehttp/main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2014-2017 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package main 13 | 14 | import ( 15 | "log" 16 | 17 | "github.com/multivactech/MultiVAC/rpc/rpcclient" 18 | ) 19 | 20 | func main() { 21 | // Connect to local bitcoin core RPC server using HTTP POST mode. 22 | connCfg := &rpcclient.ConnConfig{ 23 | Host: "localhost:8332", 24 | User: "yourrpcuser", 25 | Pass: "yourrpcpass", 26 | HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode 27 | DisableTLS: true, // Bitcoin core does not provide TLS by default 28 | } 29 | // Notice the notification parameter is nil since notifications are 30 | // not supported in HTTP POST mode. 31 | client, err := rpcclient.New(connCfg, nil) 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | defer client.Shutdown() 36 | 37 | // Get the current block count. 38 | //blockCount, err := client.GetBlockCount() 39 | //if err != nil { 40 | // log.Fatal(err) 41 | //} 42 | //log.Printf("Block count: %d", blockCount) 43 | } 44 | -------------------------------------------------------------------------------- /p2p/peer/rules.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Copyright (c) 2015-2016 The btcsuite developers 6 | // Use of this source code is governed by an ISC 7 | // license that can be found in the LICENSE file. 8 | 9 | package peer 10 | 11 | import ( 12 | "errors" 13 | "github.com/multivactech/MultiVAC/model/wire" 14 | ) 15 | 16 | // ConfirmationMessageRelyRule is the relay rule of MsgBlockConfirmation, The rules are as follows: 17 | // 1. If a peer receives the ConfirmationMessage with the same block, then returns a new message only with votes. 18 | // The votes in the message are the peer has never seen before. 19 | // 2. If a peer receives other type of message, return it. 20 | type ConfirmationMessageRelyRule struct { 21 | // todo(zhaozheng):seems unused. 22 | //message wire.Message 23 | //cache []wire.Message 24 | } 25 | 26 | // Filter filter the message which is not MsgBlockConfirmation。 27 | func (rule *ConfirmationMessageRelyRule) Filter(message wire.Message) (wire.Message, error) { 28 | 29 | // TODO(#131): complete it 30 | msg := message.(*wire.MsgBlockConfirmation) 31 | if msg == nil { 32 | return message, errors.New("can't convert message to MsgBlockConfirmation") 33 | } 34 | 35 | return msg, nil 36 | } 37 | -------------------------------------------------------------------------------- /base/util/dbUtil.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package util 6 | 7 | import ( 8 | "fmt" 9 | "github.com/multivactech/MultiVAC/base/rlp" 10 | ) 11 | 12 | const ( 13 | // KeyLedgertreeRoot is root of Ledgertree. 14 | KeyLedgertreeRoot = "LEDGERTREE_ROOT" 15 | // KeyLedgertreeLastnodehash is the Last node hash of Ledgertree. 16 | KeyLedgertreeLastnodehash = "LEDGERTREE_LASTNODEHASH" 17 | // KeyLedgertreeSize is the size of Ledgertree. 18 | KeyLedgertreeSize = "LEDGERTREE_SIZE" 19 | // KeyShardHeight is shard height. 20 | KeyShardHeight = "SHARD_HEIGHT_%d" 21 | // KeyStorageShardheight is shard height of storage node. 22 | KeyStorageShardheight = "STORAGE_SHARDHEIGHT" 23 | // KeyNodeCursor is node cursor. 24 | KeyNodeCursor = "NODE_CURSOR" 25 | ) 26 | 27 | // GetShardHeightKey returns the shard key by given shard. 28 | func GetShardHeightKey(shard uint32) []byte { 29 | res := fmt.Sprintf(KeyShardHeight, shard) 30 | return []byte(res) 31 | } 32 | 33 | // ValToByte transform val to byte array. 34 | func ValToByte(val interface{}) ([]byte, error) { 35 | res, err := rlp.EncodeToBytes(val) 36 | if err != nil { 37 | err := fmt.Errorf("EncodeToBytes err:%v", err) 38 | return nil, err 39 | } 40 | return res, nil 41 | } 42 | -------------------------------------------------------------------------------- /model/wire/msg_resendsyncreq_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | ) 11 | 12 | func fakeMsgReSendSyncReq() *MsgReSendSyncReq { 13 | 14 | return NewReSendSyncReq() 15 | } 16 | 17 | func TestReSendSyncReqEncodeDecode(t *testing.T) { 18 | msg := fakeMsgReSendSyncReq() 19 | 20 | var buf bytes.Buffer 21 | if err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding); err != nil { 22 | t.Errorf("MsgSyncInv encoding failure, err: %v", err) 23 | } 24 | rbuf := bytes.NewReader(buf.Bytes()) 25 | if err := msg.BtcDecode(rbuf, ProtocolVersion, BaseEncoding); err != nil { 26 | t.Errorf("MsgSyncInv decoding failure, err: %v", err) 27 | } 28 | } 29 | 30 | func TestReSendSyncReqCommand(t *testing.T) { 31 | msg := fakeMsgReSendSyncReq() 32 | expect := CmdReSendSyncreq 33 | if cmd := msg.Command(); cmd != expect { 34 | t.Errorf("Command want: %s, actual: %s", expect, cmd) 35 | } 36 | } 37 | 38 | func TestReSendSyncReqMaxPayloadLength(t *testing.T) { 39 | msg := fakeMsgReSendSyncReq() 40 | expect := uint32(MsgReSendSyncReqMaxPayload) 41 | if len := msg.MaxPayloadLength(ProtocolVersion); len != expect { 42 | t.Errorf("MaxPayloadLength want: %d, actual: %d", expect, len) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | 6 | Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | 9 | Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 17 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 18 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 19 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 20 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 21 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 22 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "crypto/rand" 9 | "crypto/sha1" 10 | "encoding/base64" 11 | "io" 12 | "net/http" 13 | "strings" 14 | ) 15 | 16 | // tokenListContainsValue returns true if the 1#token header with the given 17 | // name contains token. 18 | func tokenListContainsValue(header http.Header, name string, value string) bool { 19 | for _, v := range header[name] { 20 | for _, s := range strings.Split(v, ",") { 21 | if strings.EqualFold(value, strings.TrimSpace(s)) { 22 | return true 23 | } 24 | } 25 | } 26 | return false 27 | } 28 | 29 | var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") 30 | 31 | func computeAcceptKey(challengeKey string) string { 32 | h := sha1.New() 33 | _, err := h.Write([]byte(challengeKey)) 34 | if err != nil { 35 | return err.Error() 36 | } 37 | _, err = h.Write(keyGUID) 38 | if err != nil { 39 | return err.Error() 40 | } 41 | return base64.StdEncoding.EncodeToString(h.Sum(nil)) 42 | } 43 | 44 | func generateChallengeKey() (string, error) { 45 | p := make([]byte, 16) 46 | if _, err := io.ReadFull(rand.Reader, p); err != nil { 47 | return "", err 48 | } 49 | return base64.StdEncoding.EncodeToString(p), nil 50 | } 51 | -------------------------------------------------------------------------------- /processor/shared/message/pubsub.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package message 9 | 10 | // PubSubManager represents a computation unit for pub-sub pattern: https://en.wikipedia.org/wiki/Publish–subscribe_pattern 11 | // This is applied to internal in-shard broadcast communication. 12 | type PubSubManager struct { 13 | // subscribers receives the Event the PubSubManager concerns with. 14 | subscribers []Subscriber 15 | } 16 | 17 | // NewPubSubManager gives a new PubSubManager. 18 | func NewPubSubManager() *PubSubManager { 19 | return &PubSubManager{ 20 | subscribers: make([]Subscriber, 0), 21 | } 22 | } 23 | 24 | // Pub publishes the given Event to the subscribers. 25 | func (pubSubMgr *PubSubManager) Pub(evt Event) { 26 | for _, subscr := range pubSubMgr.subscribers { 27 | go subscr.Recv(evt) 28 | } 29 | } 30 | 31 | // Sub subscribes the given EventTopic with the given Subscriber. 32 | // 33 | // TODO (wangruichao@mtv.ac): need to consider concurrent safety. 34 | func (pubSubMgr *PubSubManager) Sub(subscr Subscriber) { 35 | pubSubMgr.subscribers = append(pubSubMgr.subscribers, subscr) 36 | } 37 | 38 | // Subscriber is a interface that contains a method for receiving Event. 39 | type Subscriber interface { 40 | Recv(evt Event) 41 | } 42 | -------------------------------------------------------------------------------- /testutil/mockheart.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package testutil 9 | 10 | import "github.com/multivactech/MultiVAC/model/wire" 11 | 12 | // MockHeart is heartbeat just used for testing 13 | type MockHeart struct { 14 | listsize int 15 | } 16 | 17 | // NewMockHeart returns a new instance of MockHeart 18 | func NewMockHeart(n int) *MockHeart { 19 | return &MockHeart{ 20 | listsize: n, 21 | } 22 | } 23 | 24 | // Receive used to receive heartbeat message from other nodes 25 | func (mh *MockHeart) Receive(msg *wire.HeartBeatMsg) {} 26 | 27 | // Has verfity if the pk is in whitelist 28 | func (mh *MockHeart) Has(pk []byte) bool { 29 | return true 30 | } 31 | 32 | // PerceivedCount returns the number of full network miners currently listening 33 | func (mh *MockHeart) PerceivedCount() int { 34 | return mh.listsize 35 | } 36 | 37 | // Start this module 38 | func (mh *MockHeart) Start() {} 39 | 40 | // Stop this module 41 | func (mh *MockHeart) Stop() {} 42 | 43 | // SetNumberOfList just used for testing 44 | func (mh *MockHeart) SetNumberOfList(n int) { 45 | mh.listsize = n 46 | } 47 | 48 | // CheckConfirmation implements HeatBeat interface. 49 | func (mh *MockHeart) CheckConfirmation(msg *wire.MsgBlockConfirmation) bool { 50 | return true 51 | } 52 | -------------------------------------------------------------------------------- /logger/btclog/README.md: -------------------------------------------------------------------------------- 1 | btclog 2 | ====== 3 | 4 | [![Build Status](http://img.shields.io/travis/btcsuite/btclog.svg)](https://travis-ci.org/btcsuite/btclog) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/multivactech/peer-server-test/btclog) 7 | 8 | Package btclog defines a logger interface and provides a default implementation 9 | of a subsystem-aware leveled logger implementing the same interface. 10 | 11 | ## Installation 12 | 13 | ```bash 14 | $ go get github.com/multivactech/peer-server-test/btclog 15 | ``` 16 | 17 | ## GPG Verification Key 18 | 19 | All official release tags are signed by Conformal so users can ensure the code 20 | has not been tampered with and is coming from the btcsuite developers. To 21 | verify the signature perform the following: 22 | 23 | - Download the public key from the Conformal website at 24 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 25 | 26 | - Import the public key into your GPG keyring: 27 | ```bash 28 | gpg --import GIT-GPG-KEY-conformal.txt 29 | ``` 30 | 31 | - Verify the release tag with the following command where `TAG_NAME` is a 32 | placeholder for the specific tag: 33 | ```bash 34 | git tag -v TAG_NAME 35 | ``` 36 | 37 | ## License 38 | 39 | Package btclog is licensed under the [copyfree](http://copyfree.org) ISC 40 | License. 41 | -------------------------------------------------------------------------------- /mvvm/gas.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package mvvm 9 | 10 | import ( 11 | "math" 12 | 13 | "github.com/perlin-network/life/compiler" 14 | ) 15 | 16 | var ( 17 | // mvvmGasPolicy is the gas policy for MVVM. 18 | // 19 | // In default cases, assume that each single step will consume the unit gas fee. 20 | mvvmGasPolicy = &compiler.SimpleGasPolicy{GasPerInstruction: 1} 21 | 22 | // mvvmDefaultGasLimit is the default gas limit for MVVM. 23 | // 24 | // Mostly, it is assumed that the developer will give a user-defined gas limit. But if the limit is not assigned, 25 | // mvvmDefaultGasLimit will be used as the limit value. 26 | // For now the value is set as 65535. Deeper discussion is needed. 27 | // Note that mvvmDefaultGasLimit > 0. 'cause if mvvmDefaultGasLimit <= 0, gas fee will never exceed. 28 | mvvmDefaultGasLimit int64 = 1<<16 - 1 29 | 30 | // mvvmMaxGasLimit is the maximum gas limit for MVVM. 31 | // 32 | // The MTV Coin value cost for gas is a big.Int, which is sometimes much bigger than the gas limit for life. 33 | // Hence it is assumed that if the coin value is bigger than mvvmDefaultGasLimit, the gas limit is the maximum limit. 34 | // For now this value is set as the maximum value of int64. 35 | mvvmMaxGasLimit int64 = math.MaxInt64 36 | ) 37 | -------------------------------------------------------------------------------- /logger/btclog/goclean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # The script does automatic checking on a Go package and its sub-packages, including: 3 | # 1. gofmt (http://golang.org/cmd/gofmt/) 4 | # 2. goimports (https://github.com/bradfitz/goimports) 5 | # 3. golint (https://github.com/golang/lint) 6 | # 4. go vet (http://golang.org/cmd/vet) 7 | # 5. race detector (http://blog.golang.org/race-detector) 8 | # 6. test coverage (http://blog.golang.org/cover) 9 | 10 | set -e 11 | 12 | # Automatic checks 13 | test -z $(gofmt -l -w . | tee /dev/stderr) 14 | test -z $(goimports -l -w . | tee /dev/stderr) 15 | test -z $(golint ./... | tee /dev/stderr) 16 | go vet ./... 17 | env GORACE="halt_on_error=1" go test -v -race ./... 18 | 19 | # Run test coverage on each subdirectories and merge the coverage profile. 20 | 21 | echo "mode: count" > profile.cov 22 | 23 | # Standard go tooling behavior is to ignore dirs with leading underscores. 24 | for dir in $(find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -type d) 25 | do 26 | if ls $dir/*.go &> /dev/null; then 27 | go test -covermode=count -coverprofile=$dir/profile.tmp $dir 28 | if [ -f $dir/profile.tmp ]; then 29 | cat $dir/profile.tmp | tail -n +2 >> profile.cov 30 | rm $dir/profile.tmp 31 | fi 32 | fi 33 | done 34 | 35 | # To submit the test coverage result to coveralls.io, 36 | # use goveralls (https://github.com/mattn/goveralls) 37 | # goveralls -coverprofile=profile.cov -service=travis-ci 38 | -------------------------------------------------------------------------------- /model/wire/consensus_conmmon_test.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "encoding/hex" 5 | "github.com/multivactech/MultiVAC/base/rlp" 6 | "github.com/stretchr/testify/assert" 7 | "testing" 8 | ) 9 | 10 | var ( 11 | testLeaderPublicKeyA, _ = hex.DecodeString("885f642c8390293eb74d08cf38d3333771e9e319cfd12a21429eeff2eddeebd2") 12 | testLeaderPrivateKeyA, _ = hex.DecodeString("1fcce948db9fc312902d49745249cfd287de1a764fd48afb3cd0bdd0a8d74674885f642c8390293eb74d08cf38d3333771e9e319cfd12a21429eeff2eddeebd2") 13 | ) 14 | 15 | func TestConsensusMsg_sign(t *testing.T) { 16 | var signMsg = &SignedMsg{ 17 | Pk: testLeaderPublicKeyA, 18 | } 19 | var cred = &Credential{ 20 | Round: 0, 21 | Step: 1, 22 | } 23 | 24 | err := signMsg.sign(cred, testLeaderPrivateKeyA) 25 | 26 | assert.Nil(t, err) 27 | buf, err := rlp.EncodeToBytes(cred) 28 | assert.Nil(t, err) 29 | ok, err := ed25519VRF.VerifyProof(testLeaderPublicKeyA, signMsg.Signature, buf) 30 | assert.Nil(t, err) 31 | assert.True(t, ok) 32 | } 33 | 34 | func TestConsensusMsg_isValidSignedCredential(t *testing.T) { 35 | var cred = &Credential{ 36 | Round: 0, 37 | Step: 1, 38 | } 39 | var signMsg = &SignedMsg{ 40 | Pk: testLeaderPublicKeyA, 41 | Message: ConsensusMsg{Credential: cred}, 42 | } 43 | err := signMsg.sign(cred, testLeaderPrivateKeyA) 44 | assert.Nil(t, err) 45 | 46 | err = isValidSignedCredential(signMsg.Message.Credential, signMsg) 47 | 48 | assert.Nil(t, err) 49 | } 50 | -------------------------------------------------------------------------------- /processor/miner/injector.go: -------------------------------------------------------------------------------- 1 | // +build wireinject 2 | // The build tag makes sure the stub is not built in the final build. 3 | 4 | package miner 5 | 6 | import ( 7 | di "github.com/google/wire" 8 | "github.com/multivactech/MultiVAC/interface/iabci" 9 | "github.com/multivactech/MultiVAC/interface/iblockchain" 10 | "github.com/multivactech/MultiVAC/interface/iconsensus" 11 | "github.com/multivactech/MultiVAC/interface/idepositpool" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | "github.com/multivactech/MultiVAC/processor/miner/appblockchain" 14 | "github.com/multivactech/MultiVAC/processor/miner/consensus" 15 | "github.com/multivactech/MultiVAC/processor/shared/message" 16 | ) 17 | 18 | // NewProcessor creates a miner.Processor instance which responsible for handling miner 19 | // relevant business logic. 20 | func NewProcessor(blockChain iblockchain.BlockChain, params *consensus.Params, shardIndex shard.Index, 21 | selector iconsensus.Sortitionor, dPool idepositpool.DepositPool, pubSubMgr *message.PubSubManager) *Processor { 22 | panic(di.Build(di.NewSet( 23 | provideProcessor, 24 | appblockchain.NewAppBlockChain, 25 | consensus.NewExecutor))) 26 | } 27 | 28 | func provideProcessor(shard shard.Index, abc iabci.AppBlockChain, 29 | blockChain iblockchain.BlockChain, c iconsensus.Consensus) *Processor { 30 | pcr := &Processor{shard: shard, blockChain: blockChain} 31 | pcr.abci = abc 32 | pcr.consensusExecutor = c 33 | return pcr 34 | } 35 | -------------------------------------------------------------------------------- /processor/controller/mocks/iShardRouter.go: -------------------------------------------------------------------------------- 1 | // Code generated by mockery v1.0.0. DO NOT EDIT. 2 | 3 | package mocks 4 | 5 | import ( 6 | icontroller "github.com/multivactech/MultiVAC/interface/icontroller" 7 | mock "github.com/stretchr/testify/mock" 8 | 9 | shard "github.com/multivactech/MultiVAC/model/shard" 10 | ) 11 | 12 | // MockedShardRouter is an autogenerated mock type for the MockedShardRouter type 13 | type MockedShardRouter struct { 14 | mock.Mock 15 | } 16 | 17 | // GetAllShardControllers provides a mock function with given fields: 18 | func (_m *MockedShardRouter) GetAllShardControllers() []icontroller.IShardController { 19 | ret := _m.Called() 20 | 21 | var r0 []icontroller.IShardController 22 | if rf, ok := ret.Get(0).(func() []icontroller.IShardController); ok { 23 | r0 = rf() 24 | } else { 25 | if ret.Get(0) != nil { 26 | r0 = ret.Get(0).([]icontroller.IShardController) 27 | } 28 | } 29 | 30 | return r0 31 | } 32 | 33 | // GetShardController provides a mock function with given fields: shardIndex 34 | func (_m *MockedShardRouter) GetShardController(shardIndex shard.Index) icontroller.IShardController { 35 | ret := _m.Called(shardIndex) 36 | 37 | var r0 icontroller.IShardController 38 | if rf, ok := ret.Get(0).(func(shard.Index) icontroller.IShardController); ok { 39 | r0 = rf(shardIndex) 40 | } else { 41 | if ret.Get(0) != nil { 42 | r0 = ret.Get(0).(icontroller.IShardController) 43 | } 44 | } 45 | 46 | return r0 47 | } 48 | -------------------------------------------------------------------------------- /processor/controller/rpchandler.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package controller 9 | 10 | import ( 11 | "sort" 12 | 13 | "github.com/multivactech/MultiVAC/processor/shared/message" 14 | "github.com/multivactech/MultiVAC/rpc/btcjson" 15 | ) 16 | 17 | // HandleRPCReq should be the root entry for all RPC requests to get some internal state or trigger internal operation. 18 | func (ctrl *RootController) HandleRPCReq(req *message.RPCReq) *message.RPCResp { 19 | if req.IsSharded() { 20 | if sp := ctrl.shardRouter.GetShardController(req.TargetShard); sp != nil { 21 | return sp.HandleRPCReq(req) 22 | } 23 | } else { 24 | return ctrl.handleRPCInternal(req) 25 | } 26 | return message.NewFailedRPCResp() 27 | } 28 | 29 | func (ctrl *RootController) handleRPCInternal(req *message.RPCReq) *message.RPCResp { 30 | switch req.Event { 31 | case message.RPCGetAllShardsInfo: 32 | info := &btcjson.ShardsInfo{ 33 | NumShards: len(ctrl.shardRouter.GetAllShardControllers()), 34 | } 35 | for _, sp := range ctrl.shardRouter.GetAllShardControllers() { 36 | info.Shards = append(info.Shards, btcjson.ShardInfo{Index: sp.ShardIndex(), Enabled: sp.IsEnabled()}) 37 | } 38 | sort.Sort(info) 39 | return message.NewSuccessRPCResp(info) 40 | } 41 | return message.NewFailedRPCResp() 42 | } 43 | -------------------------------------------------------------------------------- /model/merkle/ram_merkle_node.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package merkle 6 | 7 | func createRAMMerkleNode() iMerkleNode { 8 | return &ramMerkleNode{} 9 | } 10 | 11 | type ramMerkleNode struct { 12 | parent iMerkleNode 13 | leftChild iMerkleNode 14 | rightChild iMerkleNode 15 | hash *MerkleHash 16 | } 17 | 18 | func (mn *ramMerkleNode) setParent(node iMerkleNode) { 19 | mn.parent = node 20 | } 21 | 22 | func (mn *ramMerkleNode) getParent() iMerkleNode { 23 | return mn.parent 24 | } 25 | 26 | func (mn *ramMerkleNode) setLeftChild(node iMerkleNode) { 27 | mn.leftChild = node 28 | } 29 | 30 | func (mn *ramMerkleNode) getLeftChild() iMerkleNode { 31 | return mn.leftChild 32 | } 33 | 34 | func (mn *ramMerkleNode) setRightChild(node iMerkleNode) { 35 | mn.rightChild = node 36 | } 37 | 38 | func (mn *ramMerkleNode) getRightChild() iMerkleNode { 39 | return mn.rightChild 40 | } 41 | 42 | func (mn *ramMerkleNode) setHash(hash *MerkleHash) { 43 | mn.hash = hash 44 | } 45 | 46 | func (mn *ramMerkleNode) getHash() *MerkleHash { 47 | return mn.hash 48 | } 49 | 50 | func (mn *ramMerkleNode) getID() uint64 { 51 | return 0 52 | } 53 | 54 | func (mn *ramMerkleNode) isEqualTo(node iMerkleNode) bool { 55 | if n, ok := node.(*ramMerkleNode); ok { 56 | return mn == n 57 | } 58 | return false 59 | 60 | } 61 | -------------------------------------------------------------------------------- /model/wire/msg_tx_batch.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "fmt" 5 | "github.com/multivactech/MultiVAC/model/shard" 6 | "io" 7 | 8 | "github.com/multivactech/MultiVAC/base/rlp" 9 | ) 10 | 11 | // TODO Add more logic 12 | // TODO support TxWithProof 13 | 14 | // MsgTxBatch is a message is specifically used to batch Txs. 15 | type MsgTxBatch struct { 16 | ShardIndex shard.Index 17 | Txs []MsgTx 18 | } 19 | 20 | // BtcDecode decode the message. 21 | func (msg *MsgTxBatch) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 22 | return rlp.Decode(r, msg) 23 | } 24 | 25 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 26 | func (msg *MsgTxBatch) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 27 | return rlp.Encode(w, msg) 28 | } 29 | 30 | // Command returns the protocol command string for the message. 31 | func (msg *MsgTxBatch) Command() string { 32 | return CmdTxBatch 33 | } 34 | 35 | // MaxPayloadLength returns the maximum length the payload can be for the 36 | // receiver. 37 | func (msg *MsgTxBatch) MaxPayloadLength(_ uint32) uint32 { 38 | // TODO Change it to a proper value. 39 | return LargeMaxPayloadLength 40 | } 41 | 42 | func (msg *MsgTxBatch) String() string { 43 | return fmt.Sprintf("%s Index:%v, size:%d", 44 | msg.Command(), msg.ShardIndex, len(msg.Txs)) 45 | } 46 | 47 | // GetShardIndex returns the shardIndex. 48 | func (msg *MsgTxBatch) GetShardIndex() shard.Index { 49 | return msg.ShardIndex 50 | } -------------------------------------------------------------------------------- /model/chaincfg/chainhash/README.md: -------------------------------------------------------------------------------- 1 | chainhash 2 | ========= 3 | 4 | [![Build Status](http://img.shields.io/travis/btcsuite/btcd.svg)](https://travis-ci.org/btcsuite/btcd) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/multivactech/peer-server-test/chaincfg/chainhash) 7 | ======= 8 | 9 | chainhash provides a generic hash type and associated functions that allows the 10 | specific hash algorithm to be abstracted. 11 | 12 | ## Installation and Updating 13 | 14 | ```bash 15 | $ go get -u github.com/multivactech/peer-server-test/chaincfg/chainhash 16 | ``` 17 | 18 | ## GPG Verification Key 19 | 20 | All official release tags are signed by Conformal so users can ensure the code 21 | has not been tampered with and is coming from the btcsuite developers. To 22 | verify the signature perform the following: 23 | 24 | - Download the public key from the Conformal website at 25 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 26 | 27 | - Import the public key into your GPG keyring: 28 | ```bash 29 | gpg --import GIT-GPG-KEY-conformal.txt 30 | ``` 31 | 32 | - Verify the release tag with the following command where `TAG_NAME` is a 33 | placeholder for the specific tag: 34 | ```bash 35 | git tag -v TAG_NAME 36 | ``` 37 | 38 | ## License 39 | 40 | Package chainhash is licensed under the [copyfree](http://copyfree.org) ISC 41 | License. 42 | -------------------------------------------------------------------------------- /model/merkle/common_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package merkle 9 | 10 | import ( 11 | "crypto/sha256" 12 | "testing" 13 | ) 14 | 15 | func TestVerifyMerklePath(t *testing.T) { 16 | // Create a simple merkle tree 17 | a := MerkleHash(sha256.Sum256([]byte("a"))) 18 | b := MerkleHash(sha256.Sum256([]byte("b"))) 19 | c := MerkleHash(sha256.Sum256([]byte("c"))) 20 | d := MerkleHash(sha256.Sum256([]byte("d"))) 21 | ab := Hash(&a, &b, Right) 22 | cd := Hash(&c, &d, Right) 23 | abcd := Hash(ab, cd, Right) 24 | 25 | merklePath := MerklePath{ 26 | Hashes: []*MerkleHash{&b, &a, cd}, 27 | ProofPath: []byte{Left, Right}, 28 | } 29 | 30 | var err interface{} 31 | 32 | err = merklePath.Verify(abcd) 33 | if err != nil { 34 | t.Errorf("Unexpected error %s", err) 35 | } 36 | 37 | err = merklePath.Verify(cd) 38 | if _, ok := err.(RootHashMismatchError); !ok { 39 | t.Errorf("Expecting RootHashMismatchError") 40 | } 41 | } 42 | 43 | func TestIsEmptyMerkleHash(t *testing.T) { 44 | hash := &MerkleHash{} 45 | if !hash.IsEmptyHash() { 46 | t.Errorf("Hash is empty, IsEmptyHash should return True") 47 | } 48 | bts := [HashSize]byte(*hash) 49 | hash = ComputeMerkleHash(bts[:]) 50 | if hash.IsEmptyHash() { 51 | t.Errorf("Hash is not empty, IsEmptyHash should return False") 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /interface/itxprocessor/txprocessor.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package itxprocessor 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/merkle" 9 | "github.com/multivactech/MultiVAC/model/wire" 10 | ) 11 | 12 | // TxProcessor interface which executes txs for one block. 13 | // Before proposing a block, add all candidate txs into txprocessor. Then run 14 | // TxProcessor#Execute() which will generate a Result object. See interface 15 | // Result for more info about what's in it. 16 | type TxProcessor interface { 17 | AddTx(tx *wire.MsgTx) 18 | Execute(proposeHeight int64) Result 19 | } 20 | 21 | // Result of executing txs. 22 | // After executing txs, a list of new out states are generated. And a merkle 23 | // tree is build for these out states. Besides, Result interface also stores 24 | // the list of txs which are successfully executed. This list excludes txs 25 | // which encounter any error. So when proposing blocks, use the successful txs 26 | // instead of original candidate txs. 27 | type Result interface { 28 | GetOutsMerkleTree() *merkle.FullMerkleTree 29 | GetMerkleRoot() *merkle.MerkleHash 30 | GetSuccessfulTxs() []*wire.MsgTx 31 | GetOutStates() []*wire.OutState 32 | GetSmartContracts() []*wire.SmartContract 33 | GetUpdateActions() []*wire.UpdateAction 34 | GetReduceActions() []*wire.ReduceAction 35 | } 36 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/json.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "encoding/json" 9 | ) 10 | 11 | // WriteJSON is deprecated, use c.WriteJSON instead. 12 | func WriteJSON(c *Conn, v interface{}) error { 13 | return c.WriteJSON(v) 14 | } 15 | 16 | // WriteJSON writes the JSON encoding of v to the connection. 17 | // 18 | // See the documentation for encoding/json Marshal for details about the 19 | // conversion of Go values to JSON. 20 | func (c *Conn) WriteJSON(v interface{}) error { 21 | w, err := c.NextWriter(TextMessage) 22 | if err != nil { 23 | return err 24 | } 25 | err1 := json.NewEncoder(w).Encode(v) 26 | err2 := w.Close() 27 | if err1 != nil { 28 | return err1 29 | } 30 | return err2 31 | } 32 | 33 | // ReadJSON is deprecated, use c.ReadJSON instead. 34 | func ReadJSON(c *Conn, v interface{}) error { 35 | return c.ReadJSON(v) 36 | } 37 | 38 | // ReadJSON reads the next JSON-encoded message from the connection and stores 39 | // it in the value pointed to by v. 40 | // 41 | // See the documentation for the encoding/json Unmarshal function for details 42 | // about the conversion of JSON to a Go value. 43 | func (c *Conn) ReadJSON(v interface{}) error { 44 | _, r, err := c.NextReader() 45 | if err != nil { 46 | return err 47 | } 48 | return json.NewDecoder(r).Decode(v) 49 | } 50 | -------------------------------------------------------------------------------- /model/wire/msgfetchtxs.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/shard" 9 | "io" 10 | 11 | "github.com/multivactech/MultiVAC/base/rlp" 12 | ) 13 | 14 | // MsgFetchTxs is a message to request transactions from storage node. 15 | type MsgFetchTxs struct { 16 | MsgID uint32 17 | NumberOfTxs int 18 | ShardIndex shard.Index 19 | ExistTx []uint32 20 | } 21 | 22 | // BtcDecode decode the message. 23 | func (m *MsgFetchTxs) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 24 | return rlp.Decode(r, m) 25 | } 26 | 27 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 28 | func (m *MsgFetchTxs) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 29 | return rlp.Encode(w, m) 30 | } 31 | 32 | // Command returns the protocol command string for the message. 33 | func (m *MsgFetchTxs) Command() string { 34 | return CmdFetchTxs 35 | } 36 | 37 | // GetShardIndex returns the shardIndex. 38 | func (m *MsgFetchTxs) GetShardIndex() shard.Index { 39 | return m.ShardIndex 40 | } 41 | 42 | // MaxPayloadLength returns the maximum length the payload can be for the 43 | // receiver. 44 | func (m *MsgFetchTxs) MaxPayloadLength(pver uint32) uint32 { 45 | // 10k. In theory this message is very small. 46 | return 10240 47 | } 48 | -------------------------------------------------------------------------------- /processor/storagenode/wire_gen.go: -------------------------------------------------------------------------------- 1 | // Code generated by Wire. DO NOT EDIT. 2 | 3 | //go:generate wire 4 | //+build !wireinject 5 | 6 | package storagenode 7 | 8 | import ( 9 | "fmt" 10 | "github.com/multivactech/MultiVAC/interface/iblockchain" 11 | "github.com/multivactech/MultiVAC/interface/idepositpool" 12 | "github.com/multivactech/MultiVAC/interface/iheartbeat" 13 | "github.com/multivactech/MultiVAC/logger" 14 | "github.com/multivactech/MultiVAC/logger/btclog" 15 | "github.com/multivactech/MultiVAC/model/shard" 16 | ) 17 | 18 | // Injectors from injector.go: 19 | 20 | func NewStorageProcessor(shard2 shard.Index, dataDir StorageDir, blockChain iblockchain.BlockChain, dPool idepositpool.DepositPool, heartBeatManager iheartbeat.HeartBeat) *Processor { 21 | logger := provideLogger(shard2) 22 | storagenodeStorageNode := newStorageNode(shard2, dataDir, blockChain, dPool, heartBeatManager) 23 | storagenodeThreadedStorageNode := newThreadedStorageNode(shard2, storagenodeStorageNode) 24 | processor := provideProcessor(logger, storagenodeThreadedStorageNode) 25 | return processor 26 | } 27 | 28 | // injector.go: 29 | 30 | // StorageDir is defined as string type 31 | type StorageDir string 32 | 33 | func provideProcessor(logger btclog.Logger, sn *threadedStorageNode) *Processor { 34 | return &Processor{sn: sn, logger: logger} 35 | } 36 | 37 | func provideLogger(shard2 shard.Index) btclog.Logger { 38 | return logBackend.Logger(fmt.Sprintf("%s-%d", logger.StorageLoggerTag, shard2.GetID())) 39 | } 40 | -------------------------------------------------------------------------------- /rpc/rpcserver/websocket/json_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package websocket 6 | 7 | import ( 8 | "bytes" 9 | "reflect" 10 | "testing" 11 | ) 12 | 13 | func TestJSON(t *testing.T) { 14 | var buf bytes.Buffer 15 | c := fakeNetConn{&buf, &buf} 16 | wc := newConn(c, true, 1024, 1024) 17 | rc := newConn(c, false, 1024, 1024) 18 | 19 | var actual, expect struct { 20 | A int 21 | B string 22 | } 23 | expect.A = 1 24 | expect.B = "hello" 25 | 26 | if err := wc.WriteJSON(&expect); err != nil { 27 | t.Fatal("write", err) 28 | } 29 | 30 | if err := rc.ReadJSON(&actual); err != nil { 31 | t.Fatal("read", err) 32 | } 33 | 34 | if !reflect.DeepEqual(&actual, &expect) { 35 | t.Fatal("equal", actual, expect) 36 | } 37 | } 38 | 39 | func TestDeprecatedJSON(t *testing.T) { 40 | var buf bytes.Buffer 41 | c := fakeNetConn{&buf, &buf} 42 | wc := newConn(c, true, 1024, 1024) 43 | rc := newConn(c, false, 1024, 1024) 44 | 45 | var actual, expect struct { 46 | A int 47 | B string 48 | } 49 | expect.A = 1 50 | expect.B = "hello" 51 | 52 | if err := WriteJSON(wc, &expect); err != nil { 53 | t.Fatal("write", err) 54 | } 55 | 56 | if err := ReadJSON(rc, &actual); err != nil { 57 | t.Fatal("read", err) 58 | } 59 | 60 | if !reflect.DeepEqual(&actual, &expect) { 61 | t.Fatal("equal", actual, expect) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /processor/miner/wire_gen.go: -------------------------------------------------------------------------------- 1 | // Code generated by Wire. DO NOT EDIT. 2 | 3 | //go:generate wire 4 | //+build !wireinject 5 | 6 | package miner 7 | 8 | import ( 9 | "github.com/multivactech/MultiVAC/interface/iabci" 10 | "github.com/multivactech/MultiVAC/interface/iblockchain" 11 | "github.com/multivactech/MultiVAC/interface/iconsensus" 12 | "github.com/multivactech/MultiVAC/interface/idepositpool" 13 | "github.com/multivactech/MultiVAC/model/shard" 14 | "github.com/multivactech/MultiVAC/processor/miner/appblockchain" 15 | "github.com/multivactech/MultiVAC/processor/miner/consensus" 16 | "github.com/multivactech/MultiVAC/processor/shared/message" 17 | ) 18 | 19 | // Injectors from injector.go: 20 | 21 | func NewProcessor(blockChain iblockchain.BlockChain, params *consensus.Params, shardIndex shard.Index, selector iconsensus.Sortitionor, dPool idepositpool.DepositPool, pubSubMgr *message.PubSubManager) *Processor { 22 | appBlockChain := appblockchain.NewAppBlockChain(shardIndex, blockChain, dPool, pubSubMgr) 23 | iconsensusConsensus := consensus.NewExecutor(appBlockChain, selector, params) 24 | processor := provideProcessor(shardIndex, appBlockChain, blockChain, iconsensusConsensus) 25 | return processor 26 | } 27 | 28 | // injector.go: 29 | 30 | func provideProcessor(shard2 shard.Index, abc iabci.AppBlockChain, 31 | blockChain iblockchain.BlockChain, c iconsensus.Consensus) *Processor { 32 | pcr := &Processor{shard: shard2, blockChain: blockChain} 33 | pcr.abci = abc 34 | pcr.consensusExecutor = c 35 | return pcr 36 | } 37 | -------------------------------------------------------------------------------- /pos/depositpool/mail.go: -------------------------------------------------------------------------------- 1 | package depositpool 2 | 3 | import ( 4 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 5 | "github.com/multivactech/MultiVAC/model/merkle" 6 | "github.com/multivactech/MultiVAC/model/shard" 7 | "github.com/multivactech/MultiVAC/model/wire" 8 | "github.com/multivactech/MultiVAC/processor/shared/message" 9 | "github.com/multivactech/MultiVAC/processor/shared/state" 10 | ) 11 | 12 | const ( 13 | evtAddReq message.EventTopic = iota 14 | evtRemoveReq 15 | evtVerifyReq 16 | evtTopNReq 17 | evtLockReq 18 | evtUpdateReq 19 | evtDepositWithProofReq 20 | ) 21 | 22 | type reqGetAll struct { 23 | shard shard.Index 24 | address multivacaddress.Address 25 | } 26 | 27 | type addToPoolRequest struct { 28 | out *wire.OutPoint 29 | height wire.BlockHeight 30 | proof *merkle.MerklePath 31 | } 32 | 33 | type removeFromPoolRequest struct { 34 | o *wire.OutPoint 35 | } 36 | 37 | type verifyRequest struct { 38 | address multivacaddress.Address 39 | deposit []byte 40 | } 41 | 42 | type verifyResponse struct { 43 | ok bool 44 | } 45 | 46 | type refreshRequest struct { 47 | shard shard.Index 48 | update *state.Update 49 | height wire.BlockHeight 50 | } 51 | 52 | type topDepositRequest struct { 53 | address multivacaddress.Address 54 | } 55 | 56 | type topDepositResponse struct { 57 | deposit []byte 58 | err error 59 | } 60 | 61 | type getAllResponse struct { 62 | OutsWithProof []*wire.OutWithProof 63 | err error 64 | } 65 | 66 | type lockRequest struct { 67 | o *wire.OutPoint 68 | } 69 | -------------------------------------------------------------------------------- /model/wire/update_shards_message.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC dev team. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/model/shard" 11 | 12 | "github.com/multivactech/MultiVAC/base/rlp" 13 | ) 14 | 15 | // UpdatePeerInfoMessage is the message for updating shards info. 16 | type UpdatePeerInfoMessage struct { 17 | Shards []shard.Index 18 | IsDNS bool 19 | IsStorageNode bool 20 | StorageNode []string 21 | RPCListenerAddress string 22 | LocalListenerAddress string 23 | } 24 | 25 | // BtcDecode decode the message. 26 | func (msg *UpdatePeerInfoMessage) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 27 | return rlp.Decode(r, msg) 28 | } 29 | 30 | // BtcEncode serialize the message. 31 | func (msg *UpdatePeerInfoMessage) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 32 | return rlp.Encode(w, msg) 33 | } 34 | 35 | // Command returns the command string. 36 | func (msg *UpdatePeerInfoMessage) Command() string { 37 | return CmdUpdatePeerInfo 38 | } 39 | 40 | // MaxPayloadLength returns the max playlod length. 41 | func (msg *UpdatePeerInfoMessage) MaxPayloadLength(_ uint32) uint32 { 42 | // TODO Change it to a proper value. 43 | return LargeMaxPayloadLength 44 | } 45 | 46 | // GetShards returns shard index slice. 47 | func (msg *UpdatePeerInfoMessage) GetShards() []shard.Index { 48 | return msg.Shards 49 | } 50 | -------------------------------------------------------------------------------- /processor/storagenode/mail.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package storagenode 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/chaincfg/chainhash" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | "github.com/multivactech/MultiVAC/model/wire" 14 | "github.com/multivactech/MultiVAC/p2p/peer" 15 | "github.com/multivactech/MultiVAC/processor/shared/message" 16 | ) 17 | 18 | const ( 19 | evtMsgTx message.EventTopic = iota 20 | evtMsgBlock 21 | evtGetOutStateReq 22 | evtGetAllShardHgts 23 | evtGetHeaderHashes 24 | evtGetBlockReq 25 | evtGetLastConfirmation 26 | evtGetSlimBlockReq 27 | evtSlimBlock 28 | evtGetSmartContract 29 | evtGetSmartContractInfo 30 | evtMsgBlockConfirmation 31 | evtFetchMsg 32 | //evtAddSmartContractInfosToDataStore 33 | ) 34 | 35 | type getOutStateResponse struct { 36 | outState *wire.OutState 37 | err error 38 | } 39 | 40 | type fetchRequest struct { 41 | msg wire.Message 42 | peerReply peer.Reply 43 | } 44 | 45 | // Request header hashes based on locators 46 | type reqHeaderHashes struct { 47 | locators []*wire.BlockLocator 48 | } 49 | 50 | // Respond header hashes 51 | type resHeaderHashes struct { 52 | headerGroups []*wire.InvGroup 53 | } 54 | 55 | // Request a block message specified by header hash in a given shard. 56 | type getBlockReq struct { 57 | shardIdx shard.Index 58 | headerHash chainhash.Hash 59 | } 60 | -------------------------------------------------------------------------------- /base/go-socks/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012, Samuel Stauffer 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the author nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /model/wire/msgreturndeposit.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "encoding/gob" 9 | "io" 10 | 11 | "github.com/multivactech/MultiVAC/model/merkle" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | ) 14 | 15 | // OutWithProof contains outpoint and it's merkle path 16 | type OutWithProof struct { 17 | Out *OutPoint 18 | Proof *merkle.MerklePath 19 | Height BlockHeight 20 | } 21 | 22 | // MsgReturnDeposit is deposits data come from storagenode 23 | type MsgReturnDeposit struct { 24 | ShardIndex shard.Index 25 | Deposits []*OutWithProof 26 | } 27 | 28 | // BtcDecode decode the message. 29 | func (msg *MsgReturnDeposit) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 30 | decoder := gob.NewDecoder(r) 31 | return decoder.Decode(msg) 32 | } 33 | 34 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 35 | func (msg *MsgReturnDeposit) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 36 | encoder := gob.NewEncoder(w) 37 | return encoder.Encode(*msg) 38 | } 39 | 40 | // Command returns the protocol command string for the message. 41 | func (msg *MsgReturnDeposit) Command() string { 42 | return CmdReturnDeposit 43 | } 44 | 45 | // MaxPayloadLength returns the maximum length the payload can be for the 46 | // receiver. 47 | func (msg *MsgReturnDeposit) MaxPayloadLength(pver uint32) uint32 { 48 | return MaxReturnedMsgsPayload 49 | } 50 | -------------------------------------------------------------------------------- /model/wire/msgfetchinit.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "encoding/gob" 9 | "io" 10 | 11 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | ) 14 | 15 | // MsgFetchInit is a message to request ledger info from storage node. 16 | type MsgFetchInit struct { 17 | MsgID uint32 18 | ShardIndex shard.Index 19 | Address multivacaddress.Address 20 | } 21 | 22 | // BtcDecode decode the message. 23 | func (m *MsgFetchInit) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 24 | decoder := gob.NewDecoder(r) 25 | return decoder.Decode(m) 26 | } 27 | 28 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 29 | func (m *MsgFetchInit) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 30 | encoder := gob.NewEncoder(w) 31 | return encoder.Encode(*m) 32 | } 33 | 34 | // Command returns the protocol command string for the message. 35 | func (m *MsgFetchInit) Command() string { 36 | return CmdInitAbciData 37 | } 38 | 39 | // GetShardIndex returns the shardIndex. 40 | func (m *MsgFetchInit) GetShardIndex() shard.Index { 41 | return m.ShardIndex 42 | } 43 | 44 | // MaxPayloadLength returns the maximum length the payload can be for the 45 | // receiver. 46 | func (m *MsgFetchInit) MaxPayloadLength(pver uint32) uint32 { 47 | // 10k. In theory this message is very small. 48 | return 10240 49 | } 50 | -------------------------------------------------------------------------------- /p2p/connmgr/README.md: -------------------------------------------------------------------------------- 1 | connmgr 2 | ======= 3 | 4 | [![Build Status](http://img.shields.io/travis/btcsuite/btcd.svg)](https://travis-ci.org/btcsuite/btcd) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/multivactech/peer-server-test/connmgr) 7 | 8 | Package connmgr implements a generic Bitcoin network connection manager. 9 | 10 | ## Overview 11 | 12 | Connection Manager handles all the general connection concerns such as 13 | maintaining a set number of outbound connections, sourcing peers, banning, 14 | limiting max connections, tor lookup, etc. 15 | 16 | The package provides a generic connection manager which is able to accept 17 | connection requests from a source or a set of given addresses, dial them and 18 | notify the caller on connections. The main intended use is to initialize a pool 19 | of active connections and maintain them to remain connected to the P2P network. 20 | 21 | In addition the connection manager provides the following utilities: 22 | 23 | - Notifications on connections or disconnections 24 | - Handle failures and retry new addresses from the source 25 | - Connect only to specified addresses 26 | - Permanent connections with increasing backoff retry timers 27 | - Disconnect or Remove an established connection 28 | 29 | ## Installation and Updating 30 | 31 | ```bash 32 | $ go get -u github.com/multivactech/peer-server-test/connmgr 33 | ``` 34 | 35 | ## License 36 | 37 | Package connmgr is licensed under the [copyfree](http://copyfree.org) ISC License. 38 | -------------------------------------------------------------------------------- /model/wire/msgfetchdeposit.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "encoding/gob" 9 | "io" 10 | 11 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | ) 14 | 15 | // MsgFetchDeposit is a message to request deposit info from storage node. 16 | type MsgFetchDeposit struct { 17 | ShardIndex shard.Index 18 | Address multivacaddress.Address 19 | } 20 | 21 | // BtcDecode decode the message. 22 | func (msg *MsgFetchDeposit) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 23 | decoder := gob.NewDecoder(r) 24 | return decoder.Decode(msg) 25 | } 26 | 27 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 28 | func (msg *MsgFetchDeposit) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 29 | encoder := gob.NewEncoder(w) 30 | return encoder.Encode(*msg) 31 | } 32 | 33 | // Command returns the protocol command string for the message. 34 | func (msg *MsgFetchDeposit) Command() string { 35 | return CmdFetchDeposit 36 | } 37 | 38 | // MaxPayloadLength returns the maximum length the payload can be for the 39 | // receiver. 40 | func (msg *MsgFetchDeposit) MaxPayloadLength(pver uint32) uint32 { 41 | // 10k. In theory this message is very small. 42 | return 10240 43 | } 44 | 45 | // GetShardIndex returns the shardIndex. 46 | func (msg *MsgFetchDeposit) GetShardIndex() shard.Index { 47 | return msg.ShardIndex 48 | } -------------------------------------------------------------------------------- /model/chaincfg/genesis/pk.json: -------------------------------------------------------------------------------- 1 | { 2 | "pks":[ 3 | "9fad913e729bcb330b424378cbea915ff0a3464a5d20e368a5e01f2cf7f9c1f0", 4 | "38ec59eefa2523ed4faf1690d0284ae4d0808e84f40dd228288d300c69c05549", 5 | "e531db1eb2805d800539eefed5456b116a756882ef42a5910ae8a5af3f4ca1b4", 6 | "ac5f379fe49bdf5eb878ab72723b37220e0da2be6e9416d7804f3f76c82e209e", 7 | "3452ab8473d1cd128da0de0fd64563bf0eeb632b06b15c402bf10d7cce51a162", 8 | "04ce3e1adc0e0da94d59f8498942e71356ad86641c182e04ffcfb8e5451ea62b", 9 | "751e8ece6e5949d78d22c341db256cdd4a1b9cf198328b5794f79e8eaa8ff570" 10 | ], 11 | "sks":[ 12 | "80650938e7a27cc31a056af0d7e16f1e81df11dfa1c5f847104938e80a342b289fad913e729bcb330b424378cbea915ff0a3464a5d20e368a5e01f2cf7f9c1f0", 13 | "a95ea6da43dcd74b72b5d0a36601e82b2f1047fa5ba0508de26342c737570fd138ec59eefa2523ed4faf1690d0284ae4d0808e84f40dd228288d300c69c05549", 14 | "56347b68531158e5b1af5c3a74fba2608549693932b092de3219a4cc1e18d3aae531db1eb2805d800539eefed5456b116a756882ef42a5910ae8a5af3f4ca1b4", 15 | "d998bfc43169289a7af60d9719f31f48c42b86f2f0a8e9b12d90c73f5035c434ac5f379fe49bdf5eb878ab72723b37220e0da2be6e9416d7804f3f76c82e209e", 16 | "f9f6b25751c88e4126655d319da7ccac4f4ba35ad3da2afd2740e753b3da63c83452ab8473d1cd128da0de0fd64563bf0eeb632b06b15c402bf10d7cce51a162", 17 | "cf618fd3383e861c201a4966df03de2c9458d1381ee2e64f0681383a04e1d05f04ce3e1adc0e0da94d59f8498942e71356ad86641c182e04ffcfb8e5451ea62b", 18 | "b5850d545c522f13aa612d289b0853aeceb47233634dbee2d2a8a2924593fb06751e8ece6e5949d78d22c341db256cdd4a1b9cf198328b5794f79e8eaa8ff570" 19 | ] 20 | } -------------------------------------------------------------------------------- /rpc/btcjson/chainsvrwsresults_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2017 The btcsuite developers 9 | // Copyright (c) 2017 The Decred developers 10 | // Use of this source code is governed by an ISC 11 | // license that can be found in the LICENSE file. 12 | 13 | package btcjson_test 14 | 15 | import ( 16 | "encoding/json" 17 | "testing" 18 | 19 | "github.com/multivactech/MultiVAC/rpc/btcjson" 20 | ) 21 | 22 | // TestChainSvrWsResults ensures any results that have custom marshalling 23 | // work as inteded. 24 | func TestChainSvrWsResults(t *testing.T) { 25 | t.Parallel() 26 | 27 | tests := []struct { 28 | name string 29 | result interface{} 30 | expected string 31 | }{ 32 | { 33 | name: "RescannedBlock", 34 | result: &btcjson.RescannedBlock{ 35 | Hash: "blockhash", 36 | Transactions: []string{"serializedtx"}, 37 | }, 38 | expected: `{"hash":"blockhash","transactions":["serializedtx"]}`, 39 | }, 40 | } 41 | 42 | t.Logf("Running %d tests", len(tests)) 43 | for i, test := range tests { 44 | marshalled, err := json.Marshal(test.result) 45 | if err != nil { 46 | t.Errorf("Test #%d (%s) unexpected error: %v", i, 47 | test.name, err) 48 | continue 49 | } 50 | if string(marshalled) != test.expected { 51 | t.Errorf("Test #%d (%s) unexpected marhsalled data - "+ 52 | "got %s, want %s", i, test.name, marshalled, 53 | test.expected) 54 | continue 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /model/chaincfg/genesis/genesis_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package genesis 9 | 10 | import ( 11 | "crypto/sha256" 12 | "math/big" 13 | "testing" 14 | 15 | "github.com/multivactech/MultiVAC/interface/isysapi" 16 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 17 | "github.com/multivactech/MultiVAC/model/merkle" 18 | "github.com/multivactech/MultiVAC/model/shard" 19 | "github.com/multivactech/MultiVAC/model/wire" 20 | ) 21 | 22 | func TestGenesisBlock(t *testing.T) { 23 | shard := shard.ShardList[0] 24 | tx := GenerateGenesisTx(shard) 25 | txHash := tx.TxHash() 26 | setTotalAmountOfEachShard() 27 | 28 | value := new(big.Int).Div(TotalAmountOfEachShard, big.NewInt(int64(NumberOfOutsInEachGenesisBlock))) 29 | outState := &wire.OutState{ 30 | OutPoint: wire.OutPoint{ 31 | TxHash: txHash, 32 | Index: 10, 33 | UserAddress: multivacaddress.GenerateAddress(GenesisPublicKeys[shard], multivacaddress.UserAddress), 34 | Data: wire.MtvValueToData(value), 35 | ContractAddress: isysapi.SysAPIAddress, 36 | Type: wire.Transfer, 37 | }, 38 | State: wire.StateUnused, 39 | } 40 | 41 | outsHash := merkle.MerkleHash(sha256.Sum256(outState.ToBytesArray())) 42 | 43 | tree := GenesisBlocksOutsMerkleTrees[shard] 44 | outsMerklePath, _ := tree.GetMerklePath(&outsHash) 45 | 46 | if err := outsMerklePath.Verify(tree.MerkleRoot); err != nil { 47 | t.Errorf(err.Error()) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /model/wire/msg_returntxs_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | 11 | "github.com/multivactech/MultiVAC/model/shard" 12 | ) 13 | 14 | func fakeMsgReturnTxs() *MsgReturnTxs { 15 | tx := FakeTxMsgWithProof() 16 | sc := newSmartContractInfoForTest() 17 | idx := shard.Index(3) 18 | return &MsgReturnTxs{ 19 | ShardIndex: idx, 20 | Txs: []*MsgTxWithProofs{tx}, 21 | SmartContractInfos: []*SmartContractInfo{sc}, 22 | } 23 | } 24 | 25 | func TestReturnTxsEncodeDecode(t *testing.T) { 26 | msg := fakeMsgReturnTxs() 27 | var buf bytes.Buffer 28 | if err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding); err != nil { 29 | t.Errorf("MsgReturnTxs encoding failure, err: %v", err) 30 | } 31 | rbuf := bytes.NewReader(buf.Bytes()) 32 | if err := msg.BtcDecode(rbuf, ProtocolVersion, BaseEncoding); err != nil { 33 | t.Errorf("MsgReturnTxs decoding failure, err: %v", err) 34 | } 35 | } 36 | 37 | func TestReturnTxsCommand(t *testing.T) { 38 | msg := fakeMsgReturnTxs() 39 | expect := CmdReturnTxs 40 | if cmd := msg.Command(); cmd != expect { 41 | t.Errorf("Command want: %s, actual: %s", expect, cmd) 42 | } 43 | } 44 | 45 | func TestReturnTxsMaxPayloadLength(t *testing.T) { 46 | msg := fakeMsgReturnTxs() 47 | expect := uint32(MaxReturnedMsgsPayload) 48 | if len := msg.MaxPayloadLength(ProtocolVersion); len != expect { 49 | t.Errorf("MaxPayloadLength want: %d, actual: %d", expect, len) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /base/rlp/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 . 16 | 17 | // Package rlp implements the RLP serialization format. 18 | // 19 | // The purpose of RLP (Recursive Linear Prefix) is to encode arbitrarily 20 | // nested arrays of binary data, and RLP is the main encoding method used 21 | // to serialize objects in Ethereum. The only purpose of RLP is to encode 22 | // structure; encoding specific atomic data types (eg. strings, ints, 23 | // floats) is left up to higher-order protocols; in Ethereum integers 24 | // must be represented in big endian binary form with no leading zeroes 25 | // (thus making the integer value zero equivalent to the empty byte 26 | // array). 27 | // 28 | // RLP values are distinguished by a type tag. The type tag precedes the 29 | // value in the input stream and defines the size and kind of the bytes 30 | // that follow. 31 | 32 | package rlp 33 | -------------------------------------------------------------------------------- /mvvm/wasm_func.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package mvvm 9 | 10 | import "fmt" 11 | 12 | // Defination of the symbol of data type for function parameter. 13 | // 14 | // Here are the defaule data types in Clang. For user-defined data type, add length before the type name. 15 | // For example, "typedef struct {} jK" will be translated into "2jK". 16 | const ( 17 | integerParam = "i" 18 | // charParam = "c" 19 | // longLongParam = "x" 20 | // longParam = "l" 21 | // signedCharParam = "a" 22 | // shortParam = "s" 23 | // unsignedIntegerParam = "j" 24 | // unsignedCharParam = "h" 25 | // unsignedLongLongParam = "y" 26 | // unsignedLongParam = "m" 27 | // unsignedShortParam = "t" 28 | 29 | //doubleParam = "d" 30 | //floatParam = "f" 31 | //longDoubleParam = "e" 32 | 33 | //pointerParam = "P" 34 | //voidParam = "v" 35 | ) 36 | 37 | // getWasmFuncName converts the given function name f into the function name the .wast uses. 38 | // For example, if developer defines a function whose name is "whatever" with an integer parameter, the function name 39 | // in .wasm/.wast after compiling will be "_Z8whateveri", not "whatever" itself. 40 | // 41 | // Note that the conversion rule is tested after the WasmExplorer (https://mbebenita.github.io/WasmExplorer/) and the 42 | // original Golang interpreter. 43 | func getWasmFuncName(f string, params string) string { 44 | return fmt.Sprintf("_Z%d%s%s", len(f), f, params) 45 | } 46 | -------------------------------------------------------------------------------- /model/wire/msgverack.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | ) 10 | 11 | // MsgVerAck defines a bitcoin verack message which is used for a peer to 12 | // acknowledge a version message (MsgVersion) after it has used the information 13 | // to negotiate parameters. It implements the Message interface. 14 | // 15 | // This message has no payload. 16 | type MsgVerAck struct{} 17 | 18 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 19 | // This is part of the Message interface implementation. 20 | func (msg *MsgVerAck) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 21 | return nil 22 | } 23 | 24 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 25 | // This is part of the Message interface implementation. 26 | func (msg *MsgVerAck) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 27 | return nil 28 | } 29 | 30 | // Command returns the protocol command string for the message. This is part 31 | // of the Message interface implementation. 32 | func (msg *MsgVerAck) Command() string { 33 | return CmdVerAck 34 | } 35 | 36 | // MaxPayloadLength returns the maximum length the payload can be for the 37 | // receiver. This is part of the Message interface implementation. 38 | func (msg *MsgVerAck) MaxPayloadLength(pver uint32) uint32 { 39 | return 0 40 | } 41 | 42 | // NewMsgVerAck returns a new bitcoin verack message that conforms to the 43 | // Message interface. 44 | func NewMsgVerAck() *MsgVerAck { 45 | return &MsgVerAck{} 46 | } 47 | -------------------------------------------------------------------------------- /model/wire/msg_syncblock_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | 11 | "github.com/multivactech/MultiVAC/model/shard" 12 | ) 13 | 14 | const ( 15 | TestSyncBlockShardIdx = 3 16 | ) 17 | 18 | func fakeMsgSyncBlock() *MsgSyncBlock { 19 | msg := NewMsgSyncBlock(shard.Index(TestSyncBlockShardIdx), &blockOne) 20 | return msg 21 | } 22 | 23 | func TestSyncBlockEncodeDecode(t *testing.T) { 24 | msg := fakeMsgSyncBlock() 25 | var buf bytes.Buffer 26 | if err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding); err != nil { 27 | t.Errorf("MsgSyncBlock encoding failure, err: %v", err) 28 | } 29 | rbuf := bytes.NewReader(buf.Bytes()) 30 | if err := msg.BtcDecode(rbuf, ProtocolVersion, BaseEncoding); err != nil { 31 | t.Errorf("MsgSyncBlock decoding failure, err: %v", err) 32 | } 33 | if id := msg.ReqShardIdx.GetID(); id != TestSyncBlockShardIdx { 34 | t.Errorf("RequestShardIndex, expected: %v, got: %v", TestSyncBlockShardIdx, id) 35 | } 36 | } 37 | 38 | func TestSyncBlockCommand(t *testing.T) { 39 | msg := fakeMsgSyncBlock() 40 | expect := CmdSyncBlock 41 | if cmd := msg.Command(); cmd != expect { 42 | t.Errorf("Command want: %s, actual: %s", expect, cmd) 43 | } 44 | } 45 | 46 | func TestSyncBlockMaxPayloadLength(t *testing.T) { 47 | msg := fakeMsgSyncBlock() 48 | expect := uint32(MsgSyncBlockMaxPayload) 49 | if len := msg.MaxPayloadLength(ProtocolVersion); len != expect { 50 | t.Errorf("MaxPayloadLength want: %d, actual: %d", expect, len) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /model/wire/msg_returninit.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/base/rlp" 11 | "github.com/multivactech/MultiVAC/model/merkle" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | ) 14 | 15 | // MsgReturnInit defines a type of message return init. 16 | type MsgReturnInit struct { 17 | ShardIndex shard.Index 18 | MsgID uint32 19 | Ledger LedgerInfo 20 | RightPath merkle.MerklePath 21 | LatestHeader BlockHeader 22 | ShardHeight int64 23 | TreeSize int64 24 | Deposits []*OutWithProof 25 | } 26 | 27 | // BtcDecode decode the message. 28 | func (msg *MsgReturnInit) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 29 | return rlp.Decode(r, msg) 30 | } 31 | 32 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 33 | func (msg *MsgReturnInit) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 34 | return rlp.Encode(w, msg) 35 | } 36 | 37 | // Command returns the protocol command string for the message. 38 | // TODO(zz) 39 | func (msg *MsgReturnInit) Command() string { 40 | return CmdReturnInit 41 | } 42 | 43 | // MaxPayloadLength returns the maximum length the payload can be for the 44 | // receiver. 45 | // TODO? 46 | func (msg *MsgReturnInit) MaxPayloadLength(pver uint32) uint32 { 47 | return MaxReturnedMsgsPayload 48 | } 49 | 50 | // GetShardIndex returns the shardIndex. 51 | func (msg *MsgReturnInit) GetShardIndex() shard.Index { 52 | return msg.ShardIndex 53 | } 54 | -------------------------------------------------------------------------------- /model/wire/msgfetchsmartcontractinfo.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/base/rlp" 11 | "github.com/multivactech/MultiVAC/model/chaincfg/multivacaddress" 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | ) 14 | 15 | // MsgFetchSmartContractInfo is a message to request smart contract info from storage node. 16 | type MsgFetchSmartContractInfo struct { 17 | MsgID uint32 18 | ContractAddr multivacaddress.Address 19 | ShardIndex shard.Index 20 | } 21 | 22 | // BtcDecode decode the message. 23 | func (msg *MsgFetchSmartContractInfo) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 24 | return rlp.Decode(r, msg) 25 | } 26 | 27 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 28 | func (msg *MsgFetchSmartContractInfo) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 29 | return rlp.Encode(w, msg) 30 | } 31 | 32 | // Command returns the protocol command string for the message. 33 | func (msg *MsgFetchSmartContractInfo) Command() string { 34 | return CmdFetchSmartContractInfo 35 | } 36 | 37 | // MaxPayloadLength returns the maximum length the payload can be for the 38 | // receiver. 39 | func (msg *MsgFetchSmartContractInfo) MaxPayloadLength(pver uint32) uint32 { 40 | // 10k. In theory this message is very small. 41 | return 10240 42 | } 43 | 44 | // GetShardIndex returns the shardIndex. 45 | func (msg *MsgFetchSmartContractInfo) GetShardIndex() shard.Index { 46 | return msg.ShardIndex 47 | } -------------------------------------------------------------------------------- /pos/heartbeat/README.md: -------------------------------------------------------------------------------- 1 | # Package of heartbeat 2 | 3 | `heartbeat` package is used to manage the heartbeat message of miner by HeartBeatManager. HeartBeatManager is responsible for sending and receiving heartbeat messages, and it maintains a white list of legal miners, all of whom can participate in consensus vote round. 4 | 5 | ## Rules 6 | 7 | There are some rules for heartbeat: 8 | 9 | - The timestamp of each heartbeat cannot be the same 10 | - The signature of each heartbeat can be verified 11 | - The heartbeat must contains a proof of miner 12 | - The interval between sending heartbeats can't be too long 13 | - The timestamp in the heartbeat cannot differ too much from the local time. 14 | 15 | And for a miner, **the online 30min(Time can be changed) condition must be met** 16 | 17 | All time rules can be set by parameters, the parameters are in the params package(`params/params.go`): 18 | 19 | - `ONLINE_TIME_S`: The duration of a miner must be online 20 | 21 | - `TIME_DEVIATION_S`: The acceptable deviation of time for heartbeat 22 | 23 | - `SEND_HEARTBEAT_INTERVAL_S`: The interval to send heartbeat 24 | 25 | ## White list 26 | 27 | All the miners in the white list are considered legal. The miner who wants to enter the white list must abide by the following rules: 28 | 29 | - Make sure online is more than 30min 30 | - Send heartbeat frequently 31 | 32 | 33 | For testnet 34 | 35 | For testnet, the first batch of miners do not need to wait for a while, so we can adjust the time parameter by rpc. 36 | 37 | The interface is `SetHeartBeatTime`, it need three parameters: 38 | 39 | - `online` to set the miner should online time 40 | - `deviation` to set the acceptable deviation of time for heartbeat 41 | - `interval` to set interval to send heartbeat -------------------------------------------------------------------------------- /logger/level.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // This file used to set the log level of subsystem logger 6 | 7 | package logger 8 | 9 | import "github.com/multivactech/MultiVAC/logger/btclog" 10 | 11 | const ( 12 | // RootCtrlLogLevel -> RootController 13 | RootCtrlLogLevel = btclog.LevelInfo 14 | // AbciLogLevel -> abci 15 | AbciLogLevel = btclog.LevelInfo 16 | // StrgLogLevel -> storagenode 17 | StrgLogLevel = btclog.LevelInfo 18 | // SmLogLevel -> shardManager 19 | SmLogLevel = btclog.LevelInfo 20 | // ConsLogLevel -> consensus 21 | ConsLogLevel = btclog.LevelInfo 22 | // BCPLogLevel -> blockconfirmproducer 23 | BCPLogLevel = btclog.LevelInfo 24 | // ShrpLogLevel -> shardProcessor 25 | ShrpLogLevel = btclog.LevelInfo 26 | // ChainLogLevel -> chain 27 | ChainLogLevel = btclog.LevelInfo 28 | // HeartLogLevel -> heartbeat 29 | HeartLogLevel = btclog.LevelInfo 30 | // DpoolLogLevel -> depositPool 31 | DpoolLogLevel = btclog.LevelInfo 32 | // PeerLogLevel -> peer 33 | PeerLogLevel = btclog.LevelInfo 34 | // ConnectionLogLevel -> connection 35 | ConnectionLogLevel = btclog.LevelInfo 36 | // AmgrLogLevel -> addressManager 37 | AmgrLogLevel = btclog.LevelInfo 38 | // CmgrLogLevel -> connectManager 39 | CmgrLogLevel = btclog.LevelInfo 40 | // RPCLogLevel -> rpc 41 | RPCLogLevel = btclog.LevelInfo 42 | // ServerLogLevel -> server 43 | ServerLogLevel = btclog.LevelInfo 44 | // BtcdLogLevel -> btcd 45 | BtcdLogLevel = btclog.LevelInfo 46 | // SyncLogLevel -> sync 47 | SyncLogLevel = btclog.LevelInfo 48 | // TxpoolLogLevel -> txpool 49 | TxpoolLogLevel = btclog.LevelInfo 50 | ) 51 | -------------------------------------------------------------------------------- /model/wire/msg_syncslimblock_test.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/multivactech/MultiVAC/model/shard" 8 | ) 9 | 10 | // Copyright (c) 2018-present, MultiVAC Foundation. 11 | // This source code is licensed under the MIT license found in the 12 | // LICENSE file in the root directory of this source tree. 13 | 14 | const ( 15 | TestSyncSlimBlockShardIdx = 3 16 | ) 17 | 18 | func fakeMsgSyncSlimBlock() *MsgSyncSlimBlock { 19 | msg := NewMsgSyncSlimBlock(shard.Index(TestSyncSlimBlockShardIdx), &blockTwo) 20 | return msg 21 | } 22 | 23 | func TestSyncSlimBlockEncodeDecode(t *testing.T) { 24 | msg := fakeMsgSyncSlimBlock() 25 | var buf bytes.Buffer 26 | if err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding); err != nil { 27 | t.Errorf("MsgSyncSlimBlock encoding failure, err: %v", err) 28 | } 29 | rbuf := bytes.NewReader(buf.Bytes()) 30 | if err := msg.BtcDecode(rbuf, ProtocolVersion, BaseEncoding); err != nil { 31 | t.Errorf("MsgSyncSlimBlock decoding failure, err: %v", err) 32 | } 33 | if id := msg.ReqShardIdx.GetID(); id != TestSyncSlimBlockShardIdx { 34 | t.Errorf("RequestShardIndex, expected: %v, got: %v", TestSyncSlimBlockShardIdx, id) 35 | } 36 | } 37 | 38 | func TestSyncSlimBlockCommand(t *testing.T) { 39 | msg := fakeMsgSyncSlimBlock() 40 | expect := CmdSyncSlimBlock 41 | if cmd := msg.Command(); cmd != expect { 42 | t.Errorf("Command want: %s, actual: %s", expect, cmd) 43 | } 44 | } 45 | 46 | func TestSyncSlimBlockMaxPayloadLength(t *testing.T) { 47 | msg := fakeMsgSyncSlimBlock() 48 | expect := uint32(MsgSyncSlimBlockMaxPayload) 49 | if len := msg.MaxPayloadLength(ProtocolVersion); len != expect { 50 | t.Errorf("MaxPayloadLength want: %d, actual: %d", expect, len) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /model/wire/msgheartbeat.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "io" 5 | 6 | "github.com/multivactech/MultiVAC/base/rlp" 7 | ) 8 | 9 | // Timestamp defines the type of time. 10 | type Timestamp int64 11 | 12 | // HeartBeatMsg is a type of message heartbeat. 13 | type HeartBeatMsg struct { 14 | Pk []byte // the miner's public key 15 | TimeStamp Timestamp 16 | Proof []byte // the proof of a mine 17 | Signature []byte // the signature of TimeStamp 18 | } 19 | 20 | // BtcDecode decode the message. 21 | // TODO(jylu) 22 | func (msg *HeartBeatMsg) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 23 | return rlp.Decode(r, msg) 24 | } 25 | 26 | // Deserialize deserialize the data. 27 | // TODO(jylu) 28 | func (msg *HeartBeatMsg) Deserialize(r io.Reader) error { 29 | return msg.BtcDecode(r, 0, BaseEncoding) 30 | } 31 | 32 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 33 | // TODO(jylu) 34 | func (msg *HeartBeatMsg) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 35 | return rlp.Encode(w, msg) 36 | } 37 | 38 | // Serialize will serialize the message. 39 | // TODO(jylu) 40 | func (msg *HeartBeatMsg) Serialize(w io.Writer) error { 41 | return msg.BtcEncode(w, 0, BaseEncoding) 42 | } 43 | 44 | // Command returns the protocol command string for the message. This is part 45 | // of the Message interface implementation. 46 | func (msg *HeartBeatMsg) Command() string { 47 | //TODO(jylu) 48 | return CmdHeartBeat 49 | } 50 | 51 | // MaxPayloadLength returns the maximum length the payload can be for the 52 | // receiver. This is part of the Message interface implementation. 53 | func (msg *HeartBeatMsg) MaxPayloadLength(pver uint32) uint32 { 54 | //TODO(jylu) 55 | return MaxBlockPayload 56 | } 57 | -------------------------------------------------------------------------------- /model/wire/msg_syncblock.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/model/shard" 11 | 12 | "github.com/multivactech/MultiVAC/base/rlp" 13 | ) 14 | 15 | const ( 16 | // MsgSyncBlockMaxPayload is a very arbitrary number 17 | MsgSyncBlockMaxPayload = MaxBlockPayload 18 | ) 19 | 20 | // MsgSyncBlock is a type of message sync block. 21 | type MsgSyncBlock struct { 22 | ReqShardIdx shard.Index 23 | Block *MsgBlock 24 | } 25 | 26 | // NewMsgSyncBlock creates a new messagesyncblock. 27 | func NewMsgSyncBlock(s shard.Index, block *MsgBlock) *MsgSyncBlock { 28 | msg := MsgSyncBlock{} 29 | msg.ReqShardIdx = s 30 | msg.Block = block 31 | return &msg 32 | } 33 | 34 | // BtcDecode decode the message. 35 | func (msg *MsgSyncBlock) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 36 | return rlp.Decode(r, msg) 37 | } 38 | 39 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 40 | func (msg *MsgSyncBlock) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 41 | return rlp.Encode(w, msg) 42 | } 43 | 44 | // Command returns the protocol command string for the message. 45 | func (msg *MsgSyncBlock) Command() string { 46 | return CmdSyncBlock 47 | } 48 | 49 | // MaxPayloadLength returns the maximum length the payload can be for the 50 | // receiver. 51 | func (msg *MsgSyncBlock) MaxPayloadLength(uint32) uint32 { 52 | return MsgSyncBlockMaxPayload 53 | } 54 | 55 | // GetShardIndex returns the shardIndex. 56 | func (msg *MsgSyncBlock) GetShardIndex() shard.Index { 57 | return msg.ReqShardIdx 58 | } -------------------------------------------------------------------------------- /model/wire/new_round_start_message.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | // Copyright (c) 2018-present, MultiVAC dev team. 6 | // This source code is licensed under the MIT license found in the 7 | // LICENSE file in the root directory of this source tree. 8 | 9 | package wire 10 | 11 | import ( 12 | "github.com/multivactech/MultiVAC/model/shard" 13 | "io" 14 | "time" 15 | 16 | "github.com/multivactech/MultiVAC/base/rlp" 17 | 18 | "github.com/multivactech/MultiVAC/model/chaincfg/chainhash" 19 | ) 20 | 21 | // NewRoundStartMessage is the message for starting new round. 22 | type NewRoundStartMessage struct { 23 | ShardIndex shard.Index 24 | Round int 25 | Timestamp time.Time 26 | Seed chainhash.Hash 27 | Transaction *MsgTx `rlp:"nil"` 28 | } 29 | 30 | // BtcDecode decode the message. 31 | func (msg *NewRoundStartMessage) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 32 | return rlp.Decode(r, msg) 33 | } 34 | 35 | // BtcEncode encode the message. 36 | func (msg *NewRoundStartMessage) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 37 | return rlp.Encode(w, msg) 38 | } 39 | 40 | // Command returns the command string. 41 | func (msg *NewRoundStartMessage) Command() string { 42 | return CmdNewRoundStart 43 | } 44 | 45 | // MaxPayloadLength returns the max payload length 46 | func (msg *NewRoundStartMessage) MaxPayloadLength(_ uint32) uint32 { 47 | // TODO Change it to a proper value. 48 | return LargeMaxPayloadLength 49 | } 50 | 51 | // GetRound returns the round of the message. 52 | func (msg *NewRoundStartMessage) GetRound() int { 53 | return msg.Round 54 | } 55 | -------------------------------------------------------------------------------- /model/wire/msggetaddr.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | ) 10 | 11 | // MsgGetAddr implements the Message interface and represents a bitcoin 12 | // getaddr message. It is used to request a list of known active peers on the 13 | // network from a peer to help identify potential nodes. The list is returned 14 | // via one or more addr messages (MsgAddr). 15 | // 16 | // This message has no payload. 17 | type MsgGetAddr struct{} 18 | 19 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 20 | // This is part of the Message interface implementation. 21 | func (msg *MsgGetAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 22 | return nil 23 | } 24 | 25 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 26 | // This is part of the Message interface implementation. 27 | func (msg *MsgGetAddr) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 28 | return nil 29 | } 30 | 31 | // Command returns the protocol command string for the message. This is part 32 | // of the Message interface implementation. 33 | func (msg *MsgGetAddr) Command() string { 34 | return CmdGetAddr 35 | } 36 | 37 | // MaxPayloadLength returns the maximum length the payload can be for the 38 | // receiver. This is part of the Message interface implementation. 39 | func (msg *MsgGetAddr) MaxPayloadLength(pver uint32) uint32 { 40 | return 0 41 | } 42 | 43 | // NewMsgGetAddr returns a new bitcoin getaddr message that conforms to the 44 | // Message interface. See MsgGetAddr for details. 45 | func NewMsgGetAddr() *MsgGetAddr { 46 | return &MsgGetAddr{} 47 | } 48 | -------------------------------------------------------------------------------- /model/wire/protocol_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import "testing" 8 | 9 | // TestServiceFlagStringer tests the stringized output for service flag types. 10 | func TestServiceFlagStringer(t *testing.T) { 11 | tests := []struct { 12 | in ServiceFlag 13 | want string 14 | }{ 15 | {0, "0x0"}, 16 | {SFNodeNetwork, "SFNodeNetwork"}, 17 | {SFNodeGetUTXO, "SFNodeGetUTXO"}, 18 | {SFNodeBloom, "SFNodeBloom"}, 19 | {SFNodeWitness, "SFNodeWitness"}, 20 | {SFNodeXthin, "SFNodeXthin"}, 21 | {SFNodeBit5, "SFNodeBit5"}, 22 | {SFNodeCF, "SFNodeCF"}, 23 | {SFNode2X, "SFNode2X"}, 24 | {0xffffffff, "SFNodeNetwork|SFNodeGetUTXO|SFNodeBloom|SFNodeWitness|SFNodeXthin|SFNodeBit5|SFNodeCF|SFNode2X|0xffffff00"}, 25 | } 26 | 27 | t.Logf("Running %d tests", len(tests)) 28 | for i, test := range tests { 29 | result := test.in.String() 30 | if result != test.want { 31 | t.Errorf("String #%d\n got: %s want: %s", i, result, 32 | test.want) 33 | continue 34 | } 35 | } 36 | } 37 | 38 | // TestBitcoinNetStringer tests the stringized output for bitcoin net types. 39 | func TestBitcoinNetStringer(t *testing.T) { 40 | tests := []struct { 41 | in BitcoinNet 42 | want string 43 | }{ 44 | {MainNet, "MainNet"}, 45 | {TestNet, "TestNet"}, 46 | {TestNet3, "TestNet3"}, 47 | {SimNet, "SimNet"}, 48 | {0xffffffff, "Unknown BitcoinNet (4294967295)"}, 49 | } 50 | 51 | t.Logf("Running %d tests", len(tests)) 52 | for i, test := range tests { 53 | result := test.in.String() 54 | if result != test.want { 55 | t.Errorf("String #%d\n got: %s want: %s", i, result, 56 | test.want) 57 | continue 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /interface/istate/state.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package istate 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/model/merkle" 9 | "github.com/multivactech/MultiVAC/model/shard" 10 | "github.com/multivactech/MultiVAC/model/wire" 11 | "github.com/multivactech/MultiVAC/processor/shared/state" 12 | ) 13 | 14 | // LedgerStateManager is used to manage ledger statue. 15 | type LedgerStateManager interface { 16 | 17 | // LedgerInfo returns the last updated ledger info. 18 | LedgerInfo() *wire.LedgerInfo 19 | 20 | // LocalLedgerInfo returns the current local ledger. 21 | LocalLedgerInfo() *wire.LedgerInfo 22 | 23 | // GetLedgerRoot returns state's merkle tree's root hash. 24 | GetLedgerRoot() merkle.MerkleHash 25 | 26 | // GetShardHeight returns the height of the specific shrad. 27 | GetShardHeight(shardIndex shard.Index) int64 28 | 29 | // GetNewUpdate returns a temporary StateUpdate instance which can verify tx or block quickly. 30 | NewUpdate() (*state.Update, error) 31 | 32 | // ApplyUpdate apply a new update to state. 33 | ApplyUpdate(update *state.Update) error 34 | 35 | // GetUpdateWithFullBlock is similar to UpdateWithFullBlock, but it will not really update the ledger. 36 | GetUpdateWithFullBlock(block *wire.MsgBlock) (*state.Update, error) 37 | 38 | // GetUpdateWithSlimBlock is similar to GetUpdateWithFullBlock, but it updates with the slimblock rather than fullblock. 39 | GetUpdateWithSlimBlock(slimblock *wire.SlimBlock) (*state.Update, error) 40 | 41 | // It returns the available header according to the given ledgerInfo. 42 | GetBlockHeadersToAppend(ledgerInfo *wire.LedgerInfo) ([]*wire.BlockHeader, error) 43 | } 44 | -------------------------------------------------------------------------------- /model/wire/fakemessage_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import "io" 8 | 9 | // fakeMessage implements the Message interface and is used to force encode 10 | // errors in messages. 11 | type fakeMessage struct { 12 | command string 13 | payload []byte 14 | forceEncodeErr bool 15 | forceLenErr bool 16 | } 17 | 18 | // BtcDecode doesn't do anything. It just satisfies the wire.Message 19 | // interface. 20 | func (msg *fakeMessage) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 21 | return nil 22 | } 23 | 24 | // BtcEncode writes the payload field of the fake message or forces an error 25 | // if the forceEncodeErr flag of the fake message is set. It also satisfies the 26 | // wire.Message interface. 27 | func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 28 | if msg.forceEncodeErr { 29 | err := &MessageError{ 30 | Func: "fakeMessage.BtcEncode", 31 | Description: "intentional error", 32 | } 33 | return err 34 | } 35 | 36 | _, err := w.Write(msg.payload) 37 | return err 38 | } 39 | 40 | // Command returns the command field of the fake message and satisfies the 41 | // Message interface. 42 | func (msg *fakeMessage) Command() string { 43 | return msg.command 44 | } 45 | 46 | // MaxPayloadLength returns the length of the payload field of fake message 47 | // or a smaller value if the forceLenErr flag of the fake message is set. It 48 | // satisfies the Message interface. 49 | func (msg *fakeMessage) MaxPayloadLength(pver uint32) uint32 { 50 | lenp := uint32(len(msg.payload)) 51 | if msg.forceLenErr { 52 | return lenp - 1 53 | } 54 | 55 | return lenp 56 | } 57 | -------------------------------------------------------------------------------- /processor/controller/README.md: -------------------------------------------------------------------------------- 1 | 2 | [//]: <> (TODO tianhongce: Complete this document) 3 | 4 | # shardprocessor 5 | ## resharding 6 | **Detemine the next shard at H and work in the new shard at H+k**
7 | **Between the K rounds, it need to create the new shard network connection and init the ledger of new shard** 8 | * At height H: determine the next shard 9 | - before resharding in this shard, after reshading in this shard: 10 | 1. Do nothing 11 | - before resharding in this shard, after reshading not in this shard: 12 | 1. Set consensus stopped at height h+k, Since the consensus begins directly after the next round, it is necessary to set the consensus in the resharding round and stop the next round if it needs to stop. 13 | - before resharding not in this shard, after reshading in this shard: 14 | 1. Set processor enabled 15 | 2. Init ledger 16 | 3. Init ledger complete, set the miner processor status: preparation 17 | 4. Cache the block proposed by others miners 18 | 5. After receive the confirmation of the cache block, verify and accept the block 19 | 6. Broadcast the new enabledshards 20 | - before resharding not in this shard, after reshading not in this shard: 21 | 1. Do nothing 22 | * At height H+K: work in the new shard 23 | - before resharding in this shard, after reshading in this shard: 24 | 1. Update the proof 25 | - before resharding in this shard, after reshading not in this shard: 26 | 1. Consensus stopped at height h+k by itself 27 | 2. Broadcast the new enabledshards 28 | - before resharding not in this shard, after reshading in this shard: 29 | 1. Start the next round after receive the confirmation msg 30 | - before resharding not in this shard, after reshading not in this shard: 31 | 1. Do nothing 32 | -------------------------------------------------------------------------------- /rpc/btcjson/btcdextresults_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2016-2017 The btcsuite developers 9 | // Copyright (c) 2015-2016 The Decred developers 10 | // Use of this source code is governed by an ISC 11 | // license that can be found in the LICENSE file. 12 | 13 | package btcjson_test 14 | 15 | import ( 16 | "encoding/json" 17 | "testing" 18 | 19 | "github.com/multivactech/MultiVAC/rpc/btcjson" 20 | ) 21 | 22 | // TestBtcdExtCustomResults ensures any results that have custom marshalling 23 | // work as inteded. 24 | // and unmarshal code of results are as expected. 25 | func TestBtcdExtCustomResults(t *testing.T) { 26 | t.Parallel() 27 | 28 | tests := []struct { 29 | name string 30 | result interface{} 31 | expected string 32 | }{ 33 | { 34 | name: "versionresult", 35 | result: &btcjson.VersionResult{ 36 | VersionString: "1.0.0", 37 | Major: 1, 38 | Minor: 0, 39 | Patch: 0, 40 | Prerelease: "pr", 41 | BuildMetadata: "bm", 42 | }, 43 | expected: `{"versionstring":"1.0.0","major":1,"minor":0,"patch":0,"prerelease":"pr","buildmetadata":"bm"}`, 44 | }, 45 | } 46 | 47 | t.Logf("Running %d tests", len(tests)) 48 | for i, test := range tests { 49 | marshalled, err := json.Marshal(test.result) 50 | if err != nil { 51 | t.Errorf("Test #%d (%s) unexpected error: %v", i, 52 | test.name, err) 53 | continue 54 | } 55 | if string(marshalled) != test.expected { 56 | t.Errorf("Test #%d (%s) unexpected marhsalled data - "+ 57 | "got %s, want %s", i, test.name, marshalled, 58 | test.expected) 59 | continue 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /model/wire/msgrelayhash.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/base/rlp" 11 | ) 12 | 13 | // RelayHashMsg is a type of relay hash message. 14 | type RelayHashMsg struct { 15 | Relay []string 16 | Request []string 17 | } 18 | 19 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 20 | // This is part of the Message interface implementation. 21 | // TODO(jylu) 22 | func (msg *RelayHashMsg) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 23 | return rlp.Decode(r, msg) 24 | } 25 | 26 | // Deserialize will deserialize the message. 27 | // TODO(jylu) 28 | func (msg *RelayHashMsg) Deserialize(r io.Reader) error { 29 | return msg.BtcDecode(r, 0, BaseEncoding) 30 | } 31 | 32 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 33 | //TODO(jylu) 34 | func (msg *RelayHashMsg) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 35 | return rlp.Encode(w, msg) 36 | } 37 | 38 | // Serialize encodes the block to w. 39 | // TODO(jylu) 40 | func (msg *RelayHashMsg) Serialize(w io.Writer) error { 41 | return msg.BtcEncode(w, 0, BaseEncoding) 42 | } 43 | 44 | // Command returns the protocol command string for the message. This is part 45 | // of the Message interface implementation. 46 | func (msg *RelayHashMsg) Command() string { 47 | return CmdRelayHash 48 | } 49 | 50 | // MaxPayloadLength returns the maximum length the payload can be for the 51 | // receiver. This is part of the Message interface implementation. 52 | func (msg *RelayHashMsg) MaxPayloadLength(pver uint32) uint32 { 53 | return LargeMaxPayloadLength 54 | } 55 | -------------------------------------------------------------------------------- /base/rlp/encoder_example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 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 . 16 | 17 | package rlp 18 | 19 | import ( 20 | "fmt" 21 | "io" 22 | ) 23 | 24 | type MyCoolType struct { 25 | Name string 26 | a, b uint 27 | } 28 | 29 | // EncodeRLP writes x as RLP list [a, b] that omits the Name field. 30 | func (x *MyCoolType) EncodeRLP(w io.Writer) (err error) { 31 | // Note: the receiver can be a nil pointer. This allows you to 32 | // control the encoding of nil, but it also means that you have to 33 | // check for a nil receiver. 34 | if x == nil { 35 | err = Encode(w, []uint{0, 0}) 36 | } else { 37 | err = Encode(w, []uint{x.a, x.b}) 38 | } 39 | return err 40 | } 41 | 42 | func ExampleEncoder() { 43 | var t *MyCoolType // t is nil pointer to MyCoolType 44 | bytes, _ := EncodeToBytes(t) 45 | fmt.Printf("%v → %X\n", t, bytes) 46 | 47 | t = &MyCoolType{Name: "foobar", a: 5, b: 6} 48 | bytes, _ = EncodeToBytes(t) 49 | fmt.Printf("%v → %X\n", t, bytes) 50 | 51 | // Output: 52 | // → C28080 53 | // &{foobar 5 6} → C20506 54 | } 55 | -------------------------------------------------------------------------------- /model/wire/msg_syncslimblock.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/multivactech/MultiVAC/model/shard" 11 | 12 | "github.com/multivactech/MultiVAC/base/rlp" 13 | ) 14 | 15 | const ( 16 | // MsgSyncSlimBlockMaxPayload is a very arbitrary number 17 | MsgSyncSlimBlockMaxPayload = MaxBlockPayload 18 | ) 19 | 20 | // MsgSyncSlimBlock is a type of message sync block. 21 | type MsgSyncSlimBlock struct { 22 | ReqShardIdx shard.Index 23 | SlimBlock *SlimBlock 24 | } 25 | 26 | // NewMsgSyncSlimBlock creates a new messagesyncblock. 27 | func NewMsgSyncSlimBlock(s shard.Index, block *SlimBlock) *MsgSyncSlimBlock { 28 | msg := MsgSyncSlimBlock{} 29 | msg.ReqShardIdx = s 30 | msg.SlimBlock = block 31 | return &msg 32 | } 33 | 34 | // BtcDecode decode the message. 35 | func (msg *MsgSyncSlimBlock) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 36 | return rlp.Decode(r, msg) 37 | } 38 | 39 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 40 | func (msg *MsgSyncSlimBlock) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 41 | return rlp.Encode(w, msg) 42 | } 43 | 44 | // Command returns the protocol command string for the message. 45 | func (msg *MsgSyncSlimBlock) Command() string { 46 | return CmdSyncSlimBlock 47 | } 48 | 49 | // MaxPayloadLength returns the maximum length the payload can be for the 50 | // receiver. 51 | func (msg *MsgSyncSlimBlock) MaxPayloadLength(uint32) uint32 { 52 | return MsgSyncSlimBlockMaxPayload 53 | } 54 | 55 | // GetShardIndex returns the shardIndex. 56 | func (msg *MsgSyncSlimBlock) GetShardIndex() shard.Index { 57 | return msg.ReqShardIdx 58 | } -------------------------------------------------------------------------------- /base/vrf/vrf.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package vrf 6 | 7 | import "io" 8 | 9 | // PublicKey defines to be public key data structure of MultiVAC account. 10 | type PublicKey []byte 11 | 12 | // PrivateKey defines to be private key data structure of MultiVAC account. 13 | type PrivateKey []byte 14 | 15 | // VRF is named Verifiable Random Function. 16 | // See https://en.wikipedia.org/wiki//Verifable_random_function for more info. 17 | // 18 | // This class is overall in charge of all functionalities related to VRF, including generating RNG, verification, etc. 19 | // 20 | // VRF is designed to be a stateless oracle(like how it was originally designed). Caller is responsible for 21 | // rendering the private key. 22 | type VRF interface { 23 | // GenerateKey creates a public/private key pair. rnd is used for randomness. 24 | // 25 | // If rnd is nil, 'crypto/rand' is used. 26 | GenerateKey(rnd io.Reader) (pk PublicKey, sk PrivateKey, err error) 27 | 28 | // Generates a proof with given private key and public key. 29 | // 30 | // Note: the public key is not necessary. Just for efficiency. 31 | Generate(pk PublicKey, sk PrivateKey, msg []byte) (proof []byte, err error) 32 | 33 | // Verifies the proof is indeed for given message. 34 | // 35 | // Notice that the PublicKey belongs to the broadcaster of the RNG, not the node itself. 36 | VerifyProof(publicKey PublicKey, pf []byte, msg []byte) (res bool, err error) 37 | 38 | // Renders hash from proof. 39 | ProofToHash(pf []byte) []byte 40 | 41 | // TODO Clean up the API and update test for this. 42 | // Generates hash and its proof 43 | VRF(pk PublicKey, sk PrivateKey, msg []byte) (hash []byte, proof []byte, err error) 44 | } 45 | -------------------------------------------------------------------------------- /configs/params/params.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | package params 5 | 6 | const ( 7 | // LeveldbCacheMb defines the write buffer size of leveldb. 8 | LeveldbCacheMb = 64 9 | 10 | // LeveldbBlockCacheMb defines the capacity of the leveldb's 'sorted table' block caching. 11 | LeveldbBlockCacheMb = 128 12 | 13 | // LeveldbFileNumber defines the capacity of the leveldb's open files caching. 14 | LeveldbFileNumber = 64 15 | 16 | // SecurityLevel Determines whether the probability of being selected in the shard. 17 | // rand < 1 - (1 - securityLevel)^depositUnit, as mtv yellow paper. 18 | SecurityLevel = 0.8 19 | 20 | // ReshardRoundThreshold is the number of rounds that trigger resharding. 21 | // TODO(issue #127, tianhongce): Set a more reasonable threshold. 22 | ReshardRoundThreshold = 20 23 | // ReshardPrepareRoundThreshold is the number of perparation rounds before resharding. 24 | // More details about the preparation of the resharding, please see the controller/README.md. 25 | ReshardPrepareRoundThreshold = 5 26 | // RelayCache define the size of lru map. 27 | RelayCache = 1000000 28 | // DepositValue is defined that how much mtv that user has deposited can have qualifications to mine. 29 | DepositValue = 1000000 30 | // LeaderRateBase defines the number of miner who may mine block. 31 | LeaderRateBase = 20 32 | ) 33 | 34 | var ( 35 | // OnlineTimeS defines that the duration of a miner must be online. 36 | OnlineTimeS int64 = 180 37 | 38 | // TimeDeviationS defines the acceptable deviation of time for heartbeat. 39 | TimeDeviationS int64 = 100 40 | 41 | // SendHeartbeatIntervalS defines the interval to send heartbeat. 42 | SendHeartbeatIntervalS int64 = 60 43 | ) 44 | -------------------------------------------------------------------------------- /rpc/rpcclient/log.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | // Copyright (c) 2014-2017 The btcsuite developers 9 | // Use of this source code is governed by an ISC 10 | // license that can be found in the LICENSE file. 11 | 12 | package rpcclient 13 | 14 | import ( 15 | "github.com/multivactech/MultiVAC/logger/btclog" 16 | ) 17 | 18 | // log is a logger that is initialized with no output filters. This 19 | // means the package will not perform any logging by default until the caller 20 | // requests it. 21 | var log btclog.Logger 22 | 23 | // The default amount of logging is none. 24 | func init() { 25 | DisableLog() 26 | } 27 | 28 | // DisableLog disables all library log output. Logging output is disabled 29 | // by default until UseLogger is called. 30 | func DisableLog() { 31 | log = btclog.Disabled 32 | } 33 | 34 | // UseLogger uses a specified Logger to output package logging info. 35 | func UseLogger(logger btclog.Logger) { 36 | log = logger 37 | } 38 | 39 | // LogClosure is a closure that can be printed with %v to be used to 40 | // generate expensive-to-create data for a detailed log level and avoid doing 41 | // the work if the data isn't printed. 42 | //type logClosure func() string 43 | 44 | // String invokes the log closure and returns the results string. 45 | /*func (c logClosure) String() string { 46 | return c() 47 | }*/ 48 | 49 | // newLogClosure returns a new closure over the passed function which allows 50 | // it to be used as a parameter in a logging function that is only invoked when 51 | // the logging level is such that the message will actually be logged. 52 | /*func newLogClosure(c func() string) logClosure { 53 | return logClosure(c) 54 | }*/ 55 | -------------------------------------------------------------------------------- /model/wire/msg_syncheaders.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "github.com/multivactech/MultiVAC/base/rlp" 9 | "github.com/multivactech/MultiVAC/model/shard" 10 | "io" 11 | ) 12 | 13 | const ( 14 | // MsgSyncHeadersMaxPayload is a very arbitrary number 15 | MsgSyncHeadersMaxPayload = MaxBlockPayload 16 | ) 17 | 18 | // MsgSyncHeaders is used for passing back the requested header content during sync for a given shard. 19 | type MsgSyncHeaders struct { 20 | ReqShardIdx shard.Index 21 | Headers []*BlockHeader 22 | } 23 | 24 | // NewMsgSyncHeaders creates a new MsgSyncHeaders. 25 | func NewMsgSyncHeaders(s shard.Index, headers []*BlockHeader) *MsgSyncHeaders { 26 | msg := MsgSyncHeaders{} 27 | msg.ReqShardIdx = s 28 | msg.Headers = headers 29 | return &msg 30 | } 31 | 32 | // BtcDecode decode the message. 33 | func (msg *MsgSyncHeaders) BtcDecode(r io.Reader, _ uint32, _ MessageEncoding) error { 34 | return rlp.Decode(r, msg) 35 | } 36 | 37 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 38 | func (msg *MsgSyncHeaders) BtcEncode(w io.Writer, _ uint32, _ MessageEncoding) error { 39 | return rlp.Encode(w, msg) 40 | } 41 | 42 | // Command returns the protocol command string for the message. 43 | func (msg *MsgSyncHeaders) Command() string { 44 | return CmdSyncHeaders 45 | } 46 | 47 | // MaxPayloadLength returns the maximum length the payload can be for the 48 | // receiver. 49 | func (msg *MsgSyncHeaders) MaxPayloadLength(uint32) uint32 { 50 | return MsgSyncHeadersMaxPayload 51 | } 52 | 53 | // GetShardIndex returns the shardIndex. 54 | func (msg *MsgSyncHeaders) GetShardIndex() shard.Index { 55 | return msg.ReqShardIdx 56 | } -------------------------------------------------------------------------------- /model/wire/msg_syncreq_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-present, MultiVAC Foundation. 2 | // This source code is licensed under the MIT license found in the 3 | // LICENSE file in the root directory of this source tree. 4 | 5 | package wire 6 | 7 | import ( 8 | "bytes" 9 | "github.com/multivactech/MultiVAC/model/shard" 10 | "testing" 11 | ) 12 | 13 | const ( 14 | TestSyncReqShardIdx = 3 15 | ) 16 | 17 | func fakeMsgSyncReq() *MsgSyncReq { 18 | msg := NewMsgSyncReq(shard.Index(TestSyncReqShardIdx)) 19 | msg.AddBlockLocatorToRecent(shard.Index(0), 2) 20 | msg.AddBlockLocator(shard.Index(1), 4, 8) 21 | return msg 22 | } 23 | 24 | func TestSyncReqEncodeDecode(t *testing.T) { 25 | msg := fakeMsgSyncReq() 26 | var buf bytes.Buffer 27 | if err := msg.BtcEncode(&buf, ProtocolVersion, BaseEncoding); err != nil { 28 | t.Errorf("MsgSyncReq encoding failure, err: %v", err) 29 | } 30 | rbuf := bytes.NewReader(buf.Bytes()) 31 | if err := msg.BtcDecode(rbuf, ProtocolVersion, BaseEncoding); err != nil { 32 | t.Errorf("MsgSyncReq decoding failure, err: %v", err) 33 | } 34 | if id := msg.ReqShardIdx.GetID(); id != TestSyncReqShardIdx { 35 | t.Errorf("RequestShardIndex, expected: %v, got: %v", TestSyncReqShardIdx, id) 36 | } 37 | if size := len(msg.Locators); size != 2 { 38 | t.Errorf("Locator len, expected: %d, got: %d", 2, size) 39 | } 40 | } 41 | 42 | func TestSyncReqCommand(t *testing.T) { 43 | msg := fakeMsgSyncReq() 44 | expect := CmdSyncReq 45 | if cmd := msg.Command(); cmd != expect { 46 | t.Errorf("Command want: %s, actual: %s", expect, cmd) 47 | } 48 | } 49 | 50 | func TestSyncReqMaxPayloadLength(t *testing.T) { 51 | msg := fakeMsgSyncReq() 52 | expect := uint32(MsgSyncReqMaxPayload) 53 | if len := msg.MaxPayloadLength(ProtocolVersion); len != expect { 54 | t.Errorf("MaxPayloadLength want: %d, actual: %d", expect, len) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /processor/sync/state.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package sync 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/processor/shared/message" 12 | ) 13 | 14 | type syncStatus int8 15 | 16 | const ( 17 | // IDLE is a kind of status of syncState, which means waiting to sync. 18 | IDLE syncStatus = iota 19 | 20 | // RUNNING is a kind of status of syncState, which means is doing sync. 21 | RUNNING 22 | ) 23 | 24 | // const ( 25 | // maxListeners = 100 26 | // ) 27 | 28 | type syncState struct { 29 | status syncStatus 30 | pubSubMgr *message.PubSubManager 31 | } 32 | 33 | func newSyncState(pubSubMgr *message.PubSubManager) *syncState { 34 | state := syncState{ 35 | status: IDLE, 36 | pubSubMgr: pubSubMgr, 37 | } 38 | return &state 39 | } 40 | 41 | func (state *syncState) maybeStart() bool { 42 | if state.status != IDLE { 43 | log.Errorf("Attempting to start sync while it is not in IDLE mode.") 44 | return false 45 | } 46 | state.status = RUNNING 47 | state.pubSubMgr.Pub(*message.NewEvent(message.EvtSyncStart, nil)) 48 | return true 49 | } 50 | 51 | func (state *syncState) maybeStop(dataFetched bool) bool { 52 | if state.status != RUNNING { 53 | log.Errorf("Attempting to stop sync while it is not in RUNNING mode.") 54 | return false 55 | } 56 | state.status = IDLE 57 | state.pubSubMgr.Pub(*message.NewEvent(message.EvtSyncComplete, dataFetched)) 58 | return true 59 | } 60 | 61 | func (state *syncState) maybeAbort() bool { 62 | if state.status != RUNNING { 63 | log.Errorf("Attempting to abort sync while it is not in RUNNING mode.") 64 | return false 65 | } 66 | state.status = IDLE 67 | state.pubSubMgr.Pub(*message.NewEvent(message.EvtSyncAbort, nil)) 68 | return true 69 | } 70 | -------------------------------------------------------------------------------- /rpc/btcjson/export_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcjson 6 | 7 | // TstHighestUsageFlagBit makes the internal highestUsageFlagBit parameter 8 | // available to the test package. 9 | var TstHighestUsageFlagBit = highestUsageFlagBit 10 | 11 | // TstNumErrorCodes makes the internal numErrorCodes parameter available to the 12 | // test package. 13 | var TstNumErrorCodes = numErrorCodes 14 | 15 | // TstAssignField makes the internal assignField function available to the test 16 | // package. 17 | var TstAssignField = assignField 18 | 19 | // TstFieldUsage makes the internal fieldUsage function available to the test 20 | // package. 21 | var TstFieldUsage = fieldUsage 22 | 23 | // TstReflectTypeToJSONType makes the internal reflectTypeToJSONType function 24 | // available to the test package. 25 | var TstReflectTypeToJSONType = reflectTypeToJSONType 26 | 27 | // TstResultStructHelp makes the internal resultStructHelp function available to 28 | // the test package. 29 | var TstResultStructHelp = resultStructHelp 30 | 31 | // TstReflectTypeToJSONExample makes the internal reflectTypeToJSONExample 32 | // function available to the test package. 33 | var TstReflectTypeToJSONExample = reflectTypeToJSONExample 34 | 35 | // TstResultTypeHelp makes the internal resultTypeHelp function available to the 36 | // test package. 37 | var TstResultTypeHelp = resultTypeHelp 38 | 39 | // TstArgHelp makes the internal argHelp function available to the test package. 40 | var TstArgHelp = argHelp 41 | 42 | // TestMethodHelp makes the internal methodHelp function available to the test 43 | // package. 44 | var TestMethodHelp = methodHelp 45 | 46 | // TstIsValidResultType makes the internal isValidResultType function available 47 | // to the test package. 48 | var TstIsValidResultType = isValidResultType 49 | -------------------------------------------------------------------------------- /processor/miner/appblockchain/mail.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2018-present, MultiVAC Foundation. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | package appblockchain 9 | 10 | import ( 11 | "github.com/multivactech/MultiVAC/model/wire" 12 | "github.com/multivactech/MultiVAC/processor/shared/message" 13 | ) 14 | 15 | const ( 16 | evtMsg message.EventTopic = iota 17 | //evtGetShardHgtReq 18 | evtAcceptBlockReq 19 | evtVrfBlockReq 20 | evtPropBlockReq 21 | //evtGetHeaderHashes 22 | evtPropAndAcceptEmptyBlock 23 | //evtGetBlockHeader 24 | ) 25 | 26 | type proposeBlockRequest struct { 27 | pk []byte 28 | sk []byte 29 | } 30 | 31 | // Todo : not used now 32 | // type request interface{} 33 | 34 | type proposeBlockResponse struct { 35 | block *wire.MsgBlock 36 | err error 37 | } 38 | 39 | type acceptEmptyBlockResponse struct { 40 | header *wire.BlockHeader 41 | err error 42 | } 43 | 44 | // Act is executed when the given Event is catched, then the callback func will be acted. 45 | func (abc *appBlockChain) Act(e *message.Event, callback func(m interface{})) { 46 | switch e.Topic { 47 | case evtMsg: 48 | abc.onNewMessage(e.Extra.(wire.Message)) 49 | case evtVrfBlockReq: 50 | block := e.Extra.(*wire.MsgBlock) 51 | callback(abc.VerifyBlock(block)) 52 | case evtPropBlockReq: 53 | msg := e.Extra.(proposeBlockRequest) 54 | block, err := abc.ProposeBlock(msg.pk, msg.sk) 55 | callback(proposeBlockResponse{block, err}) 56 | case evtPropAndAcceptEmptyBlock: 57 | blockHeader, err := abc.ProposeAndAcceptEmptyBlock(e.Extra.(int64)) 58 | callback(acceptEmptyBlockResponse{blockHeader, err}) 59 | case evtAcceptBlockReq: 60 | msg := e.Extra.(*wire.MsgBlock) 61 | callback(abc.AcceptBlock(msg)) 62 | default: 63 | abc.log.Debugf("%v received unknown mail: %v", abc.shardIndex, e.Topic) 64 | } 65 | } 66 | --------------------------------------------------------------------------------