├── .dockerignore ├── version ├── buildversion ├── buildversion.go └── govite.go ├── smart-contract └── vite-token-bep20 │ ├── test │ └── .gitkeep │ ├── .gitignore │ ├── package.json │ └── migrations │ └── 1_initial_migration.js ├── ledger ├── pool │ ├── pool_fork_checker_test.go │ ├── pipeline_pool.go │ ├── context.go │ ├── lock │ │ ├── chain_lock_test.go │ │ └── chain_lock.go │ ├── blacklist_test.go │ ├── batch │ │ ├── level.go │ │ ├── level_snapshot.go │ │ ├── bucket.go │ │ ├── mock_chain.go │ │ ├── level_account.go │ │ └── example_test.go │ ├── face.go │ ├── tools.go │ └── tree │ │ └── printer.go ├── chain │ ├── file_manager │ │ ├── interface.go │ │ └── location.go │ ├── index │ │ ├── interface.go │ │ └── index_db_test.go │ ├── block │ │ ├── buffer.go │ │ ├── account_block.go │ │ └── snapshot_block.go │ ├── utils │ │ ├── keys_state_redo_db.go │ │ ├── keys.go │ │ └── conversion.go │ ├── cache │ │ ├── interface.go │ │ ├── unconfirmed.go │ │ ├── init.go │ │ ├── quota.go │ │ ├── cache.go │ │ └── hot_data.go │ ├── sync_cache │ │ ├── writer.go │ │ ├── segment_test.go │ │ ├── reader_test.go │ │ └── cache_item_test.go │ ├── genesis │ │ ├── interface.go │ │ └── snapshot_block.go │ ├── plugins │ │ ├── db_key_prefix.go │ │ └── onroad_info_test.go │ ├── meta.go │ ├── test_tools │ │ ├── data_dir.go │ │ └── mock.go │ ├── state │ │ └── transform_iterator.go │ ├── account.go │ └── db │ │ └── rollback.go ├── consensus │ ├── README.md │ ├── config.go │ ├── core │ │ ├── utils.go │ │ ├── time_index_test.go │ │ ├── sbp_reader_test.go │ │ ├── consensus.go │ │ └── time_index.go │ ├── cdb │ │ └── point_test.go │ ├── result.go │ ├── consensus_verifier.go │ ├── dpos.go │ └── consensus_simple_test.go ├── onroad │ ├── pool │ │ ├── error_table.go │ │ └── pool.go │ ├── reader.go │ ├── access_test.go │ ├── worker.go │ ├── task_pqueue.go │ ├── manager_test.go │ └── pending_cache_test.go ├── pipeline │ ├── pipeline_blocks_test.go │ └── blocks_test.go └── verifier │ ├── reader.go │ └── common.go ├── rpc ├── version └── inproc.go ├── bin ├── protoGen ├── bootstrap_linux ├── bootstrap ├── dump_branch_diff └── ubuntu │ ├── README.md │ └── upgrade_tar_gz.sh ├── tools └── circle │ ├── base.go │ ├── map.go │ ├── map_test.go │ └── list.go ├── crypto ├── ed25519 │ └── README.md ├── hash.go └── hast_test.go ├── .gometalinter.json ├── client ├── libwallet │ └── README.md ├── rpc │ ├── dex_trade.go │ └── tx.go ├── rpc.go └── abi_client_test.go ├── contracts-vite ├── .gitignore ├── scripts │ ├── deploy.js │ └── deploy_migrator.js ├── package.json ├── README.md ├── hardhat.config.js └── contracts │ └── ViteToken.sol ├── common ├── config │ ├── subscribe.go │ ├── wallet.go │ ├── node_reward.go │ ├── vm.go │ ├── chain.go │ ├── upgrade.go │ └── genesis_test.go ├── types │ ├── enum.go │ ├── height.go │ ├── block_source.go │ ├── jsonutils.go │ ├── hash_test.go │ ├── error.go │ ├── quota.go │ └── tokentypeid_test.go ├── vitepb │ ├── onroad.proto │ ├── account.proto │ ├── vm_log_list.proto │ ├── account_blockmeta.proto │ ├── snapshot_block.proto │ ├── sync_cache.proto │ ├── consensus_point.proto │ └── account_block.proto ├── errors │ ├── errors.go │ └── wallet_errors.go ├── helper │ ├── slice.go │ └── math_integer.go ├── mock_test.go ├── version.go ├── goroutine_test.go ├── lock.go ├── condTimeout_test.go ├── db │ └── xleveldb │ │ ├── errors.go │ │ ├── storage │ │ └── file_storage_nacl.go │ │ ├── util │ │ ├── crc32.go │ │ ├── range.go │ │ └── hash.go │ │ ├── filter.go │ │ └── comparer │ │ └── bytes_comparer.go ├── condTimer_test.go ├── goroutine.go ├── utils.go ├── log.go ├── lock_test.go ├── upgrade │ └── height_point.go ├── fileutils │ └── common_use.go ├── mock.go ├── condTimer.go └── lifecycle.go ├── interfaces ├── core │ ├── serializable.go │ ├── snapshot_chunk.go │ ├── token.go │ ├── info.go │ ├── hash_height_test.go │ └── account.go ├── consensus.go ├── verifier.go ├── wallet.go └── generator.go ├── log15 ├── term │ ├── terminal_netbsd.go │ ├── terminal_openbsd.go │ ├── terminal_solaris.go │ ├── terminal_appengine.go │ ├── terminal_darwin.go │ ├── terminal_linux.go │ ├── terminal_freebsd.go │ ├── terminal_notwindows.go │ ├── terminal_windows.go │ └── LICENSE ├── handler_go14.go ├── LICENSE ├── handler_go13.go └── CONTRIBUTORS ├── cmd ├── utils │ ├── customFlags_test.go │ ├── path.go │ ├── flock │ │ ├── flock_plan9.go │ │ ├── flock_windows.go │ │ ├── flock_darwin.go │ │ ├── flock_linux.go │ │ ├── flock.go │ │ └── flock_solaris.go │ └── cli.go ├── nodemanager │ ├── node_manager.go │ ├── node_maker.go │ ├── subcmd_node_manager.go │ ├── default_node_manager.go │ ├── assist.go │ └── export_node_manager.go ├── gvite │ └── main.go ├── generator │ └── wallet │ │ └── main.go ├── printer │ ├── index │ │ └── main.go │ └── blocks │ │ └── main.go ├── updater_consensus │ └── main.go ├── updater │ └── main.go ├── subcmd_check_chain │ └── check_chain.go ├── subcmd_plugin_data │ └── plugin_data_cmd.go ├── subcmd_export │ └── export.go ├── subcmd_recover │ └── subcmd_recover.go └── gvite_plugins │ └── subcmd_demo.go ├── net ├── netool │ └── net_test.go ├── vnode │ ├── host.go │ ├── node.proto │ ├── mode.go │ ├── host_test.go │ └── mock.go ├── discovery │ ├── finder.go │ └── protos │ │ └── message.proto ├── sync_state_test.go ├── sync_server_test.go ├── block_feed_test.go └── mock_receiver.go ├── rpcapi └── api │ ├── common_error.go │ ├── debug.go │ ├── health.go │ ├── dex │ └── util.go │ └── virtual.go ├── producer ├── producerevent │ └── event.go ├── face.go └── worker_test.go ├── pow └── remote │ ├── request.go │ └── response.go ├── vm_db ├── builtin_contract.go ├── debug.go ├── account_block.go ├── storage_iterator.go ├── storage.go ├── snapshot_block.go ├── balance.go ├── state.go └── vm_log.go ├── vm ├── abi │ ├── numbers_test.go │ ├── Variable.go │ └── numbers.go ├── util │ └── types.go ├── test │ ├── interpreter_test │ │ ├── random.json │ │ ├── stop.json │ │ ├── codesize.json │ │ ├── arith.json │ │ ├── callvalue.json │ │ ├── balance.json │ │ ├── address.json │ │ └── caller.json │ └── run_test │ │ └── send_call.json ├── stack_table.go ├── contracts │ ├── abi │ │ └── util.go │ └── dex │ │ └── utils_test.go ├── params.go └── gas_table_test.go ├── .github ├── workflows │ ├── README.md │ ├── dispatch-nightly-build.yml │ └── nightly-build.yml └── PULL_REQUEST_TEMPLATE.md ├── docker ├── Dockerfile.preBuild ├── README.md └── Dockerfile ├── conf ├── evm │ ├── vite_3167c9421c8a4cb642d613082dfcef932e26063867f277ec0f │ ├── node_config.json │ └── README.md └── node_config.json ├── ledger_snapshot.md ├── monitor ├── monitor_test.go └── ring_test.go ├── node └── errors.go ├── wallet ├── hd-bip │ ├── derivation │ │ └── bip_main_test.go │ └── main │ │ └── main.go ├── account_test.go ├── entropystore │ └── models.go └── wallet.go ├── .gitignore └── vite_mock.go /.dockerignore: -------------------------------------------------------------------------------- 1 | docker/* 2 | -------------------------------------------------------------------------------- /version/buildversion: -------------------------------------------------------------------------------- 1 | v2.14.0 2 | -------------------------------------------------------------------------------- /smart-contract/vite-token-bep20/test/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ledger/pool/pool_fork_checker_test.go: -------------------------------------------------------------------------------- 1 | package pool 2 | -------------------------------------------------------------------------------- /rpc/version: -------------------------------------------------------------------------------- 1 | 62e94895da80838ec694b4ba19eeac80c9dc88c1 2 | 3 | -------------------------------------------------------------------------------- /bin/protoGen: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | protoc --go_out=. common/vitepb/*.proto 4 | -------------------------------------------------------------------------------- /smart-contract/vite-token-bep20/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/* 2 | cache/* 3 | artifacts/* 4 | build/* 5 | -------------------------------------------------------------------------------- /tools/circle/base.go: -------------------------------------------------------------------------------- 1 | package circle 2 | 3 | type Key = interface{} 4 | type Value = interface{} 5 | -------------------------------------------------------------------------------- /crypto/ed25519/README.md: -------------------------------------------------------------------------------- 1 | this is Ed25519 Go implementation that uses blake2b hash function instead of sha512 -------------------------------------------------------------------------------- /.gometalinter.json: -------------------------------------------------------------------------------- 1 | { 2 | "Disable": [ 3 | "gocyclo", 4 | "varcheck", 5 | "structcheck" 6 | ] 7 | } -------------------------------------------------------------------------------- /client/libwallet/README.md: -------------------------------------------------------------------------------- 1 | cd client/libwallet/ 2 | 3 | go build -buildmode=c-shared -i -o libvitewallet.dylib wallet.go -------------------------------------------------------------------------------- /contracts-vite/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/* 2 | cache/* 3 | artifacts/* 4 | .openzeppelin/* 5 | dist/* 6 | scripts/dist/* 7 | -------------------------------------------------------------------------------- /common/config/subscribe.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Subscribe struct { 4 | IsSubscribe bool `json:"IsSubscribe"` 5 | } 6 | -------------------------------------------------------------------------------- /common/config/wallet.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Wallet struct { 4 | DataDir string 5 | MaxSearchIndex uint32 6 | } 7 | -------------------------------------------------------------------------------- /common/types/enum.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | type Enum interface { 4 | name() string 5 | ordinal() int 6 | values() *[]string 7 | } 8 | -------------------------------------------------------------------------------- /common/vitepb/onroad.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package vitepb; 4 | 5 | message OnroadMeta { 6 | uint64 num = 1; 7 | bytes amount = 2; 8 | } -------------------------------------------------------------------------------- /interfaces/core/serializable.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | type Serializable interface { 4 | Serialize() ([]byte, error) 5 | Deserialize([]byte) error 6 | } 7 | -------------------------------------------------------------------------------- /common/vitepb/account.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package vitepb; 4 | 5 | message Account { 6 | uint64 accountId = 1; 7 | bytes publicKey = 2; 8 | } -------------------------------------------------------------------------------- /log15/term/terminal_netbsd.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import "syscall" 4 | 5 | const ioctlReadTermios = syscall.TIOCGETA 6 | 7 | type Termios syscall.Termios 8 | -------------------------------------------------------------------------------- /log15/term/terminal_openbsd.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import "syscall" 4 | 5 | const ioctlReadTermios = syscall.TIOCGETA 6 | 7 | type Termios syscall.Termios 8 | -------------------------------------------------------------------------------- /version/buildversion.go: -------------------------------------------------------------------------------- 1 | package version 2 | const VITE_COMMIT_VERSION = "142a4f6fa0ed50d24ceaa6445e03da91b6bf8999" 3 | const VITE_BUILD_VERSION = "v2.14.0" 4 | -------------------------------------------------------------------------------- /bin/bootstrap_linux: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | echo "=====================================================================" >> gvite.log 5 | 6 | nohup ./gvite >> gvite.log 2>&1 & -------------------------------------------------------------------------------- /ledger/chain/file_manager/interface.go: -------------------------------------------------------------------------------- 1 | package chain_file_manager 2 | 3 | type DataParser interface { 4 | Write([]byte) error 5 | WriteError(err error) 6 | Close() error 7 | } 8 | -------------------------------------------------------------------------------- /ledger/consensus/README.md: -------------------------------------------------------------------------------- 1 | Generate `MockChain`: 2 | 3 | ``` 4 | ~/go/bin/mockgen -source=ledger/consensus/chain_rw.go -destination=ledger/consensus/mock_ch.go -package=consensus 5 | ``` -------------------------------------------------------------------------------- /common/types/height.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | var EmptyHeight = uint64(0) 4 | var GenesisHeight = uint64(1) 5 | 6 | const ( 7 | HeightSize = 8 8 | AccountIdSize = 8 9 | ) 10 | -------------------------------------------------------------------------------- /bin/bootstrap: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | echo "=====================================================================" >> gvite.log 5 | 6 | nohup ulimit -n 40960; ./gvite >> gvite.log 2>&1 & -------------------------------------------------------------------------------- /cmd/utils/customFlags_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "os/user" 5 | "testing" 6 | ) 7 | 8 | func TestPathExpansion(t *testing.T) { 9 | 10 | user.Current() 11 | 12 | } 13 | -------------------------------------------------------------------------------- /common/config/node_reward.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type NodeReward struct { 4 | RewardAddr string `json:"RewardAddr"` 5 | Name string `json:"Name"` 6 | SecretPub *string `json:"SecretPub"` 7 | } 8 | -------------------------------------------------------------------------------- /interfaces/core/snapshot_chunk.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | type SnapshotChunk struct { 4 | SnapshotBlock *SnapshotBlock `json:"snapshotBlock"` 5 | AccountBlocks []*AccountBlock `json:"accountBlocks"` 6 | } 7 | -------------------------------------------------------------------------------- /common/errors/errors.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | import "errors" 4 | 5 | // Common errors. 6 | var ( 7 | NotFound = errors.New("error: Not Found") 8 | NotMatch = errors.New("error: Not Match") 9 | ) 10 | -------------------------------------------------------------------------------- /ledger/pool/pipeline_pool.go: -------------------------------------------------------------------------------- 1 | package pool 2 | 3 | import "github.com/vitelabs/go-vite/v2/net" 4 | 5 | func (pl *pool) AddPipeline(reader net.ChunkReader) { 6 | pl.pipelines = append(pl.pipelines, reader) 7 | } 8 | -------------------------------------------------------------------------------- /ledger/pool/context.go: -------------------------------------------------------------------------------- 1 | package pool 2 | 3 | type poolContext struct { 4 | compactDirty bool 5 | } 6 | 7 | func (context *poolContext) setCompactDirty(dirty bool) { 8 | context.compactDirty = dirty 9 | } 10 | -------------------------------------------------------------------------------- /cmd/nodemanager/node_manager.go: -------------------------------------------------------------------------------- 1 | package nodemanager 2 | 3 | import "github.com/vitelabs/go-vite/v2/node" 4 | 5 | type NodeManager interface { 6 | Start() error 7 | 8 | Stop() error 9 | 10 | Node() *node.Node 11 | } 12 | -------------------------------------------------------------------------------- /common/vitepb/vm_log_list.proto: -------------------------------------------------------------------------------- 1 | syntax="proto3"; 2 | 3 | package vitepb; 4 | 5 | message VmLog { 6 | repeated bytes topics = 1; 7 | bytes data = 2; 8 | } 9 | 10 | message VmLogList { 11 | repeated VmLog list = 1; 12 | } -------------------------------------------------------------------------------- /ledger/consensus/config.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | type ConsensusCfg struct { 4 | } 5 | 6 | func DefaultCfg() *ConsensusCfg { 7 | return &ConsensusCfg{} 8 | } 9 | 10 | func Cfg() *ConsensusCfg { 11 | return &ConsensusCfg{} 12 | } 13 | -------------------------------------------------------------------------------- /smart-contract/vite-token-bep20/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "truffle-plugin-verify": "^0.5.8" 4 | }, 5 | "dependencies": { 6 | "truffle-hdwallet-provider": "^1.0.17", 7 | "truffle-ledger-provider": "^1.0.3" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /common/helper/slice.go: -------------------------------------------------------------------------------- 1 | package helper 2 | 3 | import "reflect" 4 | 5 | func ReverseSlice(s interface{}) { 6 | size := reflect.ValueOf(s).Len() 7 | swap := reflect.Swapper(s) 8 | for i, j := 0, size-1; i < j; i, j = i+1, j-1 { 9 | swap(i, j) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /common/vitepb/account_blockmeta.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package vitepb; 4 | 5 | message AccountBlockMeta { 6 | uint64 accountId = 1; 7 | uint64 height = 2; 8 | repeated uint64 receiveBlockHeights = 3; 9 | uint64 refSnapshotHeight = 4; 10 | } -------------------------------------------------------------------------------- /interfaces/core/token.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | var ViteTokenId = types.TokenTypeId{'V', 'I', 'T', 'E', ' ', 'T', 'O', 'K', 'E', 'N'} 6 | var VCPTokenId, _ = types.HexToTokenTypeId("tti_251a3e67a41b5ea2373936c8") 7 | -------------------------------------------------------------------------------- /common/config/vm.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | type Vm struct { 4 | IsVmTest bool `json:"IsVmTest"` 5 | IsUseVmTestParam bool `json:"IsUseVmTestParam"` 6 | IsUseQuotaTestParam bool `json:"IsUseQuotaTestParam"` 7 | IsVmDebug bool `json:"IsVmDebug"` 8 | } 9 | -------------------------------------------------------------------------------- /smart-contract/vite-token-bep20/migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const TokenContract = artifacts.require("CoinToken"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(TokenContract, "Vite", "VITE", 18, 1, "0x047F2837372358bD867DB94D0f0E93388004d0Cc"); 5 | }; -------------------------------------------------------------------------------- /net/netool/net_test.go: -------------------------------------------------------------------------------- 1 | package netool 2 | 3 | import "testing" 4 | 5 | func TestCheckRelayIP(t *testing.T) { 6 | sender := []byte{192, 168, 0, 0} 7 | ip := []byte{0, 0, 0, 0} 8 | 9 | if CheckRelayIP(sender, ip) == nil { 10 | t.Error("should error") 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /log15/term/terminal_solaris.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import "golang.org/x/sys/unix" 4 | 5 | // IsTty returns true if the given file descriptor is chain terminal. 6 | func IsTty(fd uintptr) bool { 7 | _, err := unix.IoctlGetTermios(int(fd), unix.TCGETA) 8 | return err == nil 9 | } 10 | -------------------------------------------------------------------------------- /net/vnode/host.go: -------------------------------------------------------------------------------- 1 | package vnode 2 | 3 | type HostType byte 4 | 5 | const ( 6 | HostIPv4 HostType = 1 7 | HostIPv6 HostType = 2 8 | HostIP HostType = 3 9 | HostDomain HostType = 4 10 | ) 11 | 12 | func (ht HostType) Is(ht2 HostType) bool { 13 | return ht&ht2 > 0 14 | } 15 | -------------------------------------------------------------------------------- /ledger/consensus/core/utils.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | func ConvertVoteToAddress(votes []*Vote) []types.Address { 6 | var result []types.Address 7 | for _, v := range votes { 8 | result = append(result, v.Addr) 9 | } 10 | return result 11 | } 12 | -------------------------------------------------------------------------------- /common/mock_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestMockAddress(t *testing.T) { 9 | address := MockAddress(99) 10 | fmt.Println(address.String()) 11 | } 12 | 13 | func TestMockHash(t *testing.T) { 14 | hash := MockHash(99) 15 | fmt.Println(hash.String()) 16 | } 17 | -------------------------------------------------------------------------------- /common/version.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "sync/atomic" 5 | ) 6 | 7 | type Version struct { 8 | version uint64 9 | } 10 | 11 | func (self *Version) Inc() { 12 | atomic.AddUint64(&self.version, 1) 13 | } 14 | 15 | func (self *Version) Val() uint64 { 16 | return atomic.LoadUint64(&self.version) 17 | } 18 | -------------------------------------------------------------------------------- /cmd/utils/path.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "path/filepath" 4 | 5 | // AbsolutePath returns datadir + filename, or filename if it is absolute. 6 | func AbsolutePath(datadir string, filename string) string { 7 | if filepath.IsAbs(filename) { 8 | return filename 9 | } 10 | return filepath.Join(datadir, filename) 11 | } 12 | -------------------------------------------------------------------------------- /ledger/chain/index/interface.go: -------------------------------------------------------------------------------- 1 | package chain_index 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | type Chain interface { 9 | IterateContracts(iterateFunc func(addr types.Address, meta *ledger.ContractMeta, err error) bool) 10 | } 11 | -------------------------------------------------------------------------------- /rpcapi/api/common_error.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrStrToBigInt = errors.New("convert to big.Int failed") 7 | ErrPoWNotSupportedUnderCongestion = errors.New("PoW service not supported") 8 | ErrDifficultyTooLarge = errors.New("difficulty is too large") 9 | ) 10 | -------------------------------------------------------------------------------- /rpcapi/api/debug.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | type Deprecated struct { 4 | } 5 | 6 | func NewDeprecated() *Deprecated { 7 | return &Deprecated{} 8 | } 9 | 10 | func (p Deprecated) String() string { 11 | return "DeprecatedApi" 12 | } 13 | 14 | func (p *Deprecated) Hello() (string, error) { 15 | return "hello world", nil 16 | } 17 | -------------------------------------------------------------------------------- /cmd/gvite/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "net/http/pprof" 5 | 6 | "github.com/vitelabs/go-vite/v2/cmd/gvite_plugins" 7 | "github.com/vitelabs/go-vite/v2/version" 8 | ) 9 | 10 | // gvite is the official command-line client for Vite 11 | 12 | func main() { 13 | version.PrintBuildVersion() 14 | gvite_plugins.Loading() 15 | } 16 | -------------------------------------------------------------------------------- /net/vnode/node.proto: -------------------------------------------------------------------------------- 1 | syntax="proto3"; 2 | 3 | package vnode; 4 | 5 | message pNode { 6 | bytes id = 1; 7 | bytes hostname = 2; 8 | uint32 hostType = 3; 9 | uint32 port = 4; 10 | uint32 net = 5; 11 | bytes ext = 6; 12 | } 13 | 14 | message pEndPoint { 15 | bytes host = 1; 16 | int32 port = 2; 17 | int32 hostType = 3; 18 | } 19 | -------------------------------------------------------------------------------- /producer/producerevent/event.go: -------------------------------------------------------------------------------- 1 | package producerevent 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | type AccountEvent interface { 10 | } 11 | 12 | type AccountStartEvent struct { 13 | AccountEvent 14 | Gid types.Gid 15 | Address types.Address 16 | Stime time.Time 17 | Etime time.Time 18 | } 19 | -------------------------------------------------------------------------------- /version/govite.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import "fmt" 4 | 5 | // For "govendor install" 6 | 7 | func PrintBuildVersion() { 8 | if VITE_COMMIT_VERSION != "" { 9 | fmt.Printf("this vite node`s version(%s), git commit %s, ", VITE_BUILD_VERSION, VITE_COMMIT_VERSION) 10 | } else { 11 | fmt.Println("can not read gitversion file please use Make to build Vite ") 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /common/goroutine_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestGo(t *testing.T) { 10 | Go(func() { 11 | fmt.Println("hello world") 12 | //panic(errors.New("test error")) 13 | var s *sss 14 | 15 | println(s.aaa) 16 | 17 | }) 18 | 19 | time.Sleep(time.Second) 20 | } 21 | 22 | type sss struct { 23 | aaa string 24 | } 25 | -------------------------------------------------------------------------------- /producer/face.go: -------------------------------------------------------------------------------- 1 | package producer 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/producer/producerevent" 6 | ) 7 | 8 | type Producer interface { 9 | SetAccountEventFunc(func(producerevent.AccountEvent)) 10 | Init() error 11 | Start() error 12 | Stop() error 13 | GetCoinBase() types.Address 14 | SnapshotOnce() error 15 | } 16 | -------------------------------------------------------------------------------- /pow/remote/request.go: -------------------------------------------------------------------------------- 1 | package remote 2 | 3 | type workGenerate struct { 4 | DataHash string `json:"hash"` 5 | Threshold string `json:"threshold"` 6 | } 7 | 8 | type workValidate struct { 9 | DataHash string `json:"hash"` 10 | Threshold string `json:"threshold"` 11 | Work string `json:"work"` 12 | } 13 | 14 | type workCancel struct { 15 | DataHash string `json:"hash"` 16 | } 17 | -------------------------------------------------------------------------------- /log15/term/terminal_appengine.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by chain BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build appengine 7 | 8 | package term 9 | 10 | // IsTty always returns false on AppEngine. 11 | func IsTty(fd uintptr) bool { 12 | return false 13 | } 14 | -------------------------------------------------------------------------------- /log15/term/terminal_darwin.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by chain BSD-style 4 | // license that can be found in the LICENSE file. 5 | // +build !appengine 6 | 7 | package term 8 | 9 | import "syscall" 10 | 11 | const ioctlReadTermios = syscall.TIOCGETA 12 | 13 | type Termios syscall.Termios 14 | -------------------------------------------------------------------------------- /log15/term/terminal_linux.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2013 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by chain BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build !appengine 7 | 8 | package term 9 | 10 | import "syscall" 11 | 12 | const ioctlReadTermios = syscall.TCGETS 13 | 14 | type Termios syscall.Termios 15 | -------------------------------------------------------------------------------- /common/types/block_source.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | type BlockSource uint16 4 | 5 | const ( 6 | Unkonwn BlockSource = 0 7 | RemoteBroadcast = 10 8 | RemoteFetch = 20 9 | Local = 30 10 | RollbackChain = 40 11 | QueryChain = 41 12 | RemoteSync = 50 13 | RemoteCache = 60 14 | ) 15 | -------------------------------------------------------------------------------- /interfaces/core/info.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | type AccountInfo struct { 10 | AccountAddress types.Address 11 | TotalNumber uint64 12 | TokenBalanceInfoMap map[types.TokenTypeId]*TokenBalanceInfo 13 | } 14 | 15 | type TokenBalanceInfo struct { 16 | TotalAmount big.Int 17 | Number uint64 18 | } 19 | -------------------------------------------------------------------------------- /ledger/consensus/core/time_index_test.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func Test_Time2Index(t *testing.T) { 11 | genesis := time.Unix(1552708800, 0) 12 | ti := NewTimeIndex(genesis, time.Hour*24) 13 | t2 := time.Unix(1556251200, 0) 14 | index := ti.Time2Index(t2) 15 | assert.Equal(t, uint64(41), index) 16 | 17 | } 18 | -------------------------------------------------------------------------------- /ledger/chain/block/buffer.go: -------------------------------------------------------------------------------- 1 | package chain_block 2 | 3 | import ( 4 | "encoding/binary" 5 | 6 | "github.com/golang/snappy" 7 | ) 8 | 9 | func makeWriteBytes(buf []byte, dataType byte, data []byte) []byte { 10 | 11 | buf[4] = dataType 12 | sBuf := snappy.Encode(buf[5:], data) 13 | sBufLen := len(sBuf) 14 | 15 | binary.BigEndian.PutUint32(buf, uint32(sBufLen+1)) 16 | 17 | return buf[:5+sBufLen] 18 | } 19 | -------------------------------------------------------------------------------- /net/discovery/finder.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import "github.com/vitelabs/go-vite/v2/net/vnode" 4 | 5 | type Observer interface { 6 | Sub(sub Subscriber) 7 | UnSub(sub Subscriber) 8 | } 9 | 10 | type Finder interface { 11 | Observer 12 | SetResolver(discv interface { 13 | GetNodes(count int) (nodes []*vnode.Node) 14 | }) 15 | FindNeighbors(fromId, target vnode.NodeID, count int) []*vnode.EndPoint 16 | } 17 | -------------------------------------------------------------------------------- /bin/dump_branch_diff: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## example: ./bin/dump_branch_diff v2.10.2 v2.10.3-rc1 5 | 6 | echo $1 $2 7 | 8 | git log $1..$2 --pretty=format:%h,%ae > commits-logs/commits.log 9 | 10 | for params in `cat commits-logs/commits.log | xargs echo`; do id=`echo $params | awk -F "," '{print $1}'`; name=`echo $params | awk -F "," '{print $2}'`; git show $id --name-only --pretty="format:### %H,%an,%ae,%s" >> commits-logs/$name; done; -------------------------------------------------------------------------------- /cmd/nodemanager/node_maker.go: -------------------------------------------------------------------------------- 1 | package nodemanager 2 | 3 | import ( 4 | "gopkg.in/urfave/cli.v1" 5 | 6 | "github.com/vitelabs/go-vite/v2/node" 7 | nodeconfig "github.com/vitelabs/go-vite/v2/node/config" 8 | ) 9 | 10 | type NodeMaker interface { 11 | 12 | //create Node 13 | MakeNode(ctx *cli.Context) (*node.Node, error) 14 | 15 | //create NodeConfig 16 | MakeNodeConfig(ctx *cli.Context) (*nodeconfig.Config, error) 17 | } 18 | -------------------------------------------------------------------------------- /cmd/utils/flock/flock_plan9.go: -------------------------------------------------------------------------------- 1 | package flock 2 | 3 | import "os" 4 | 5 | type plan9Lock struct { 6 | f *os.File 7 | } 8 | 9 | func (l *plan9Lock) Release() error { 10 | return l.f.Close() 11 | } 12 | 13 | func newLock(fileName string) (Releaser, error) { 14 | f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModeExclusive|0644) 15 | if err != nil { 16 | return nil, err 17 | } 18 | return &plan9Lock{f}, nil 19 | } 20 | -------------------------------------------------------------------------------- /common/types/jsonutils.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrJsonNotString = errors.New("not valid string") 7 | ) 8 | 9 | func isString(input []byte) bool { 10 | return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' 11 | } 12 | 13 | func trimLeftRightQuotation(input []byte) []byte { 14 | if isString(input) { 15 | return input[1 : len(input)-1] 16 | } 17 | return []byte{} 18 | } 19 | -------------------------------------------------------------------------------- /ledger/consensus/core/sbp_reader_test.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "math/big" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestBigInt(t *testing.T) { 11 | n := big.NewInt(10) 12 | 13 | bt := BigInt{Int: n} 14 | 15 | bt2 := bt.SetInt64(11) 16 | 17 | t.Log(bt.String(), bt2.String()) 18 | 19 | assert.Equal(t, bt.String(), "11") 20 | assert.Equal(t, bt2.String(), "11") 21 | } 22 | -------------------------------------------------------------------------------- /common/vitepb/snapshot_block.proto: -------------------------------------------------------------------------------- 1 | syntax="proto3"; 2 | 3 | package vitepb; 4 | 5 | 6 | message SnapshotBlock { 7 | bytes hash = 1; 8 | bytes prevHash = 2; 9 | uint64 height = 3; 10 | bytes publicKey = 4; 11 | 12 | bytes signature = 5; 13 | 14 | int64 timestamp = 6; 15 | 16 | uint64 Seed = 7; 17 | 18 | bytes SeedHash = 8; 19 | 20 | bytes snapshotContent = 9; 21 | 22 | uint32 version = 10; 23 | } -------------------------------------------------------------------------------- /log15/term/terminal_freebsd.go: -------------------------------------------------------------------------------- 1 | package term 2 | 3 | import ( 4 | "syscall" 5 | ) 6 | 7 | const ioctlReadTermios = syscall.TIOCGETA 8 | 9 | // Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin. 10 | type Termios struct { 11 | Iflag uint32 12 | Oflag uint32 13 | Cflag uint32 14 | Lflag uint32 15 | Cc [20]uint8 16 | Ispeed uint32 17 | Ospeed uint32 18 | } 19 | -------------------------------------------------------------------------------- /pow/remote/response.go: -------------------------------------------------------------------------------- 1 | package remote 2 | 3 | type ResponseJson struct { 4 | Code int `json:"code"` 5 | Data interface{} `json:"data"` 6 | Error string `json:"error"` 7 | Msg string `json:"msg"` 8 | } 9 | 10 | type workGenerateResult struct { 11 | Work string `json:"work"` 12 | } 13 | 14 | type workCancelResult struct { 15 | } 16 | 17 | type workValidateResult struct { 18 | Valid string `json:"valid"` 19 | } 20 | -------------------------------------------------------------------------------- /vm_db/builtin_contract.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "errors" 5 | "math/big" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | ) 9 | 10 | func (vdb *vmDb) GetStakeBeneficialAmount(addr *types.Address) (*big.Int, error) { 11 | if vdb.latestSnapshotBlockHash == nil { 12 | return nil, errors.New("no context, vdb.latestSnapshotBlockHash is nil") 13 | } 14 | 15 | return vdb.chain.GetStakeBeneficialAmount(*addr) 16 | } 17 | -------------------------------------------------------------------------------- /vm/abi/numbers_test.go: -------------------------------------------------------------------------------- 1 | package abi 2 | 3 | import ( 4 | "bytes" 5 | "math/big" 6 | "testing" 7 | 8 | "github.com/vitelabs/go-vite/v2/common/helper" 9 | ) 10 | 11 | func TestNumberTypes(t *testing.T) { 12 | ubytes := make([]byte, helper.WordSize) 13 | ubytes[helper.WordSize-1] = 1 14 | 15 | unsigned := U256(big.NewInt(1)) 16 | if !bytes.Equal(unsigned, ubytes) { 17 | t.Errorf("expected %x got %x", ubytes, unsigned) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ledger/pool/lock/chain_lock_test.go: -------------------------------------------------------------------------------- 1 | package lock 2 | 3 | import "testing" 4 | 5 | func TestLock(t *testing.T) { 6 | impl := &EasyImpl{} 7 | impl.LockInsert() 8 | impl.UnLockInsert() 9 | impl.LockRollback() 10 | impl.UnLockRollback() 11 | impl.RLockRollback() 12 | impl.RLockRollback() 13 | impl.RUnLockRollback() 14 | impl.RUnLockRollback() 15 | impl.RLockInsert() 16 | impl.RLockInsert() 17 | impl.RUnLockInsert() 18 | impl.RUnLockInsert() 19 | } 20 | -------------------------------------------------------------------------------- /cmd/generator/wallet/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | "github.com/vitelabs/go-vite/v2/wallet" 8 | ) 9 | 10 | var num = flag.Int("num", 1, "num ") 11 | 12 | func main() { 13 | flag.Parse() 14 | for i := 0; i < *num; i++ { 15 | addr, key, mnemonic, err := wallet.RandomMnemonic24() 16 | if err != nil { 17 | panic(err) 18 | } 19 | fmt.Printf("address:%s, key:%s, mnemonic:%s\n", addr, key.Hex(), mnemonic) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ledger/consensus/cdb/point_test.go: -------------------------------------------------------------------------------- 1 | package cdb 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestContent_Copy(t *testing.T) { 10 | point := &Content{ExpectedNum: 13, FactualNum: 11} 11 | 12 | copy := point.Copy() 13 | 14 | copy.FactualNum = 10 15 | 16 | t.Log(copy.FactualNum, point.FactualNum) 17 | 18 | assert.Equal(t, copy.FactualNum, uint32(10)) 19 | assert.Equal(t, point.FactualNum, uint32(11)) 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/README.md: -------------------------------------------------------------------------------- 1 | # Workflows 2 | 3 | ## Create Personal Access Token (PAT): 4 | 5 | - Login on GitHub as vitelabs-bot 6 | - Go to https://github.com/settings/tokens 7 | - Generate new token 8 | - Note: WORKFLOW_PUBLIC_REPO 9 | - Expiration: No expiration 10 | - Select scopes: repo -> public_repo 11 | 12 | ## Add repo secret 13 | 14 | - Go to Settings -> Secrects -> Actions 15 | - New repository secret 16 | - Name: WORKFLOW_PUBLIC_REPO_PAT 17 | - Value: ghp_... 18 | -------------------------------------------------------------------------------- /vm_db/debug.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | func (vdb *vmDb) DebugGetStorage() (map[string][]byte, error) { 4 | result := make(map[string][]byte) 5 | iter, err := vdb.NewStorageIterator(nil) 6 | if err != nil { 7 | return nil, err 8 | } 9 | 10 | defer iter.Release() 11 | 12 | for iter.Next() { 13 | result[string(iter.Key())] = iter.Value() 14 | } 15 | if err := iter.Error(); err != nil { 16 | return nil, iter.Error() 17 | } 18 | 19 | return result, nil 20 | } 21 | -------------------------------------------------------------------------------- /common/vitepb/sync_cache.proto: -------------------------------------------------------------------------------- 1 | syntax="proto3"; 2 | 3 | package vitepb; 4 | 5 | import "vitepb/message.proto"; 6 | 7 | message cacheItem { 8 | uint64 from = 1; 9 | uint64 to = 2; 10 | bytes prevHash = 3; 11 | bytes hash = 4; 12 | repeated vitepb.HashHeight points = 5; 13 | bool verified = 6; 14 | string filename = 7; 15 | bool done = 8; 16 | int64 size = 9; 17 | } 18 | 19 | message cacheItems { 20 | repeated cacheItem items = 1; 21 | } 22 | -------------------------------------------------------------------------------- /docker/Dockerfile.preBuild: -------------------------------------------------------------------------------- 1 | FROM alpine:3.8 2 | 3 | RUN apk update \ 4 | && apk upgrade \ 5 | && apk add --no-cache bash \ 6 | bash-doc \ 7 | bash-completion \ 8 | && rm -rf /var/cache/apk/* \ 9 | && /bin/bash 10 | 11 | RUN apk add --no-cache ca-certificates 12 | 13 | WORKDIR /root 14 | 15 | COPY build/cmd/gvite/gvite-*-linux/gvite . 16 | COPY ./conf conf 17 | COPY ./conf/node_config.json . 18 | 19 | EXPOSE 8483 8484 48132 41420 8483/udp 20 | ENTRYPOINT ["./gvite"] 21 | -------------------------------------------------------------------------------- /vm_db/account_block.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | func (vdb *vmDb) GetUnconfirmedBlocks(address types.Address) []*ledger.AccountBlock { 9 | return vdb.chain.GetUnconfirmedBlocks(address) 10 | } 11 | func (vdb *vmDb) GetLatestAccountBlock(addr types.Address) (*ledger.AccountBlock, error) { 12 | return vdb.chain.GetLatestAccountBlock(addr) 13 | } 14 | -------------------------------------------------------------------------------- /contracts-vite/scripts/deploy.js: -------------------------------------------------------------------------------- 1 | // scripts/deploy.js 2 | async function main() { 3 | const ERC20 = await ethers.getContractFactory("ViteToken"); 4 | console.log("Deploying ERC20 ..."); 5 | const erc20 = await ERC20.deploy(); 6 | await erc20.deployed(); 7 | console.log("deployed to:", erc20.address); 8 | } 9 | 10 | main() 11 | .then(() => process.exit(0)) 12 | .catch(error => { 13 | console.error(error); 14 | process.exit(1); 15 | }); 16 | -------------------------------------------------------------------------------- /common/errors/wallet_errors.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrLocked = errors.New("the crypto store is locked") 7 | ErrAddressNotFound = errors.New("not found the given address in the crypto store file") 8 | ErrInvalidPrikey = errors.New("invalid prikey") 9 | ErrDecryptEntropy = errors.New("error decrypt store") 10 | ErrEmptyStore = errors.New("error empty store") 11 | ErrStoreNotFound = errors.New("error given store not found ") 12 | ) 13 | -------------------------------------------------------------------------------- /conf/evm/vite_3167c9421c8a4cb642d613082dfcef932e26063867f277ec0f: -------------------------------------------------------------------------------- 1 | {"primaryAddress":"vite_3167c9421c8a4cb642d613082dfcef932e26063867f277ec0f","crypto":{"ciphername":"aes-256-gcm","ciphertext":"cb3f586df80c30286d34561de23001ad88520286b5a989b4ca924fc2dd558dda2db80474ff855163fd69923dcf7dfb7c","nonce":"5af9960c6da5bc131f6d2f52","kdf":"scrypt","scryptparams":{"n":262144,"r":8,"p":1,"keylen":32,"salt":"faf3388c33ed78bf3aefaa2303471e92888e5325439b888cb6fdc555551916c3"}},"seedstoreversion":1,"timestamp":1630764810} -------------------------------------------------------------------------------- /ledger/chain/utils/keys_state_redo_db.go: -------------------------------------------------------------------------------- 1 | package chain_utils 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | // ------------------------------- 6 | type SnapshotKey [1 + types.HeightSize]byte 7 | 8 | func (key SnapshotKey) Bytes() []byte { 9 | return key[:] 10 | } 11 | 12 | func (key SnapshotKey) String() string { 13 | return string(key[:]) 14 | } 15 | 16 | func (key *SnapshotKey) HeightRefill(height uint64) { 17 | Uint64Put(key[1:1+types.HeightSize], height) 18 | } 19 | -------------------------------------------------------------------------------- /ledger/onroad/pool/error_table.go: -------------------------------------------------------------------------------- 1 | package onroad_pool 2 | 3 | import "errors" 4 | 5 | var ( 6 | // OnRoadPool 7 | ErrOnRoadPoolNotAvailable = errors.New("target gid's onRoadPool is not available") 8 | ErrCheckIsCallerFrontOnRoadFailed = errors.New("onRoadPool check the Caller's front onroad hash failed") 9 | 10 | //panic 11 | ErrLoadCallerCacheFailed = errors.New("load callerCache failed") 12 | ErrFindCompleteBlock = errors.New("failed to find complete block by hash") 13 | ) 14 | -------------------------------------------------------------------------------- /ledger_snapshot.md: -------------------------------------------------------------------------------- 1 | ## Ledger Snapshots 2 | 3 | Building a full node faster from a snapshot. 4 | 5 | Thanks to [ANKR](http://ankr.com) for sponsoring the download: 6 | 7 | http://chains-jg.dccn.ankr.com/download/ledger.tar.gz 8 | 9 | SHA256(ledger.tar.gz)=6341764adb7e4edc0467be71042bc3f9ecdadf7bf8d019d17ddc52379753e0b1 10 | 11 | ```bash 12 | cd ~/.gvite/maindata/ 13 | mv ledger ledger_bk 14 | wget -c http://chains-jg.dccn.ankr.com/download/ledger.tar.gz 15 | tar -xzvf ledger.tar.gz 16 | ``` 17 | -------------------------------------------------------------------------------- /vm/abi/Variable.go: -------------------------------------------------------------------------------- 1 | package abi 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | // Variable is used only in built-in contracts 9 | type Variable struct { 10 | Name string 11 | Inputs Arguments 12 | } 13 | 14 | func (v Variable) String() string { 15 | inputs := make([]string, len(v.Inputs)) 16 | for i, input := range v.Inputs { 17 | inputs[i] = fmt.Sprintf("%v %v", input.Type, input.Name) 18 | } 19 | return fmt.Sprintf("struct %v { %v }", v.Name, strings.Join(inputs, ",")) 20 | } 21 | -------------------------------------------------------------------------------- /common/types/hash_test.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestHashCmp(t *testing.T) { 10 | hash1, err := HexToHash("0000000000000000000000000000000000000000000000000000000000000001") 11 | assert.NoError(t, err) 12 | hash2, err := HexToHash("0000000000000000000000000000000000000000000000000000000000000002") 13 | assert.NoError(t, err) 14 | 15 | result := hash1.Cmp(hash2) 16 | 17 | assert.True(t, result == -1) 18 | } 19 | -------------------------------------------------------------------------------- /vm/util/types.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 5 | ) 6 | 7 | // GlobalStatus contains confirm snapshot block and seed of contract response block 8 | type GlobalStatus interface { 9 | Seed() (uint64, error) // Random number, returns same number 10 | Random() (uint64, error) // Random number, returns different number every time calls 11 | SnapshotBlock() *ledger.SnapshotBlock // Confirm snapshot block of send block 12 | } 13 | -------------------------------------------------------------------------------- /common/types/error.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "errors" 4 | 5 | var ( 6 | // ErrGetLatestAccountBlock defines the error about failing to get latest account block from chain db 7 | ErrGetLatestAccountBlock = errors.New("get latest account block failed") 8 | // ErrGetLatestSnapshotBlock defines the error about failing to get latest snapshot block from chain db 9 | ErrGetLatestSnapshotBlock = errors.New("get latest snapshot block failed") 10 | 11 | ErrVmRunPanic = errors.New("generator_vm panic error") 12 | ) 13 | -------------------------------------------------------------------------------- /common/vitepb/consensus_point.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package vitepb; 4 | 5 | message PointVoteContent { 6 | bytes voteCnt = 1; 7 | string name = 2; 8 | } 9 | 10 | 11 | message PointContent { 12 | bytes address = 1; 13 | fixed32 fNum = 2; 14 | fixed32 eNum = 3; 15 | } 16 | 17 | message ConsensusPoint { 18 | bytes prevHash = 1; 19 | bytes hash = 2; 20 | 21 | repeated PointContent contents = 7; 22 | 23 | repeated PointVoteContent votes = 8; 24 | } 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /interfaces/consensus.go: -------------------------------------------------------------------------------- 1 | package interfaces 2 | 3 | import ( 4 | "math/big" 5 | "time" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | "github.com/vitelabs/go-vite/v2/ledger/consensus/core" 9 | ) 10 | 11 | type VoteDetails struct { 12 | core.Vote 13 | CurrentAddr types.Address 14 | RegisterList []types.Address 15 | Addr map[types.Address]*big.Int 16 | } 17 | 18 | type TimeIndex interface { 19 | Index2Time(index uint64) (time.Time, time.Time) 20 | Time2Index(t time.Time) uint64 21 | } 22 | -------------------------------------------------------------------------------- /interfaces/verifier.go: -------------------------------------------------------------------------------- 1 | package interfaces 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | // ConsensusVerifier is the interface that can verify block consensus. 9 | type ConsensusVerifier interface { 10 | VerifyAccountProducer(block *core.AccountBlock) (bool, error) 11 | VerifyABsProducer(abs map[types.Gid][]*core.AccountBlock) ([]*core.AccountBlock, error) 12 | VerifySnapshotProducer(block *core.SnapshotBlock) (bool, error) 13 | } 14 | -------------------------------------------------------------------------------- /contracts-vite/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "contracts-vite", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "author": "viteshan", 6 | "license": "GPL-3.0", 7 | "devDependencies": { 8 | "@nomiclabs/hardhat-ethers": "^2.0.1", 9 | "@nomiclabs/hardhat-waffle": "^2.0.1", 10 | "chai": "^4.3.0", 11 | "ethereum-waffle": "^3.3.0", 12 | "ethers": "^5.0.31", 13 | "hardhat": "^2.0.11", 14 | "keccak256": "^1.0.2" 15 | }, 16 | "dependencies": { 17 | "@openzeppelin/contracts": "3.3.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | **What kind of change does this PR introduce?** (check at least one) 5 | 6 | - [ ] Improvement 7 | - [ ] Bugfix 8 | - [ ] Feature 9 | - [ ] Refactor 10 | - [ ] Other, please describe: 11 | 12 | **Does this PR introduce a breaking change?** (check one) 13 | 14 | - [ ] Yes 15 | - [ ] No 16 | 17 | If yes, please describe the impact and migration path for existing applications: 18 | 19 | 20 | **Other information:** 21 | -------------------------------------------------------------------------------- /vm/test/interpreter_test/random.json: -------------------------------------------------------------------------------- 1 | { 2 | "SEED": { 3 | "amount": "0de0b6b3a7640000", 4 | "code": "60004a55", 5 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 6 | "inputData": "", 7 | "quotaLeft": 9795, 8 | "quotaTotal": 10000, 9 | "sBHeight": 1, 10 | "storage": { 11 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000" 12 | }, 13 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 14 | "tokenID": "tti_2445f6e5cde8c2c70e446c83" 15 | } 16 | } -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Build 4 | 5 | ``` 6 | cd `go env GOPATH`/src/github.com/vitelabs/go-vite 7 | 8 | docker build -t vitelabs/gvite:test -f docker/Dockerfile . 9 | 10 | ``` 11 | 12 | 13 | # Run With Docker 14 | 15 | ``` 16 | docker run -v $HOME/.gvite/:/root/.gvite/ -p 48132:48132 -p 41420:41420 -p 8483:8483 -p 8484:8484 -p 8483:8483/udp -d vitelabs/gvite:test 17 | ``` 18 | 19 | 20 | 21 | # quickly Build from local binary 22 | 23 | ``` 24 | gvite-linux 25 | docker build -t vitelabs/gvite-nightly:test . -f docker/Dockerfile.preBuild 26 | ``` -------------------------------------------------------------------------------- /ledger/chain/cache/interface.go: -------------------------------------------------------------------------------- 1 | package chain_cache 2 | 3 | import ( 4 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 5 | ) 6 | 7 | type Chain interface { 8 | QueryLatestSnapshotBlock() (*ledger.SnapshotBlock, error) 9 | QuerySnapshotBlockByHeight(height uint64) (*ledger.SnapshotBlock, error) 10 | GetSnapshotBlockByHeight(height uint64) (*ledger.SnapshotBlock, error) 11 | 12 | GetSubLedger(endHeight, startHeight uint64) ([]*ledger.SnapshotChunk, error) 13 | GetSubLedgerAfterHeight(height uint64) ([]*ledger.SnapshotChunk, error) 14 | } 15 | -------------------------------------------------------------------------------- /bin/ubuntu/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | install vite as linux service 4 | # install v2.10.3-rc3 5 | 6 | ``` 7 | curl -s https://raw.githubusercontent.com/vitelabs/go-vite/master/bin/ubuntu/install_tar_gz.sh | bash -s v2.10.3-rc3 8 | ``` 9 | 10 | # upgrade to version v2.10.3-rc3 11 | 12 | ``` 13 | curl -s https://raw.githubusercontent.com/vitelabs/go-vite/master/bin/ubuntu/upgrade_tar_gz.sh | bash -s v2.10.3-rc3 14 | ``` 15 | 16 | # start 17 | 18 | ``` 19 | sudo service vite start 20 | ``` 21 | 22 | # stop 23 | 24 | ``` 25 | sudo service vite stop 26 | ``` 27 | 28 | -------------------------------------------------------------------------------- /common/config/chain.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | // chain config 6 | type Chain struct { 7 | LedgerGcRetain uint64 // no use 8 | GenesisFile string // genesis file path 9 | LedgerGc bool // open or close ledger garbage collector 10 | OpenPlugins bool // open or close chain plugins. eg, filter account blocks by token. 11 | 12 | VmLogWhiteList []types.Address // contract address white list which save VM logs 13 | VmLogAll bool // save all VM logs, it will cost more disk space 14 | } 15 | -------------------------------------------------------------------------------- /vm/test/run_test/send_call.json: -------------------------------------------------------------------------------- 1 | { 2 | "send_call_to_non_exist_contract_before_hardfork": { 3 | "sbHeight": 1, 4 | "blockType": 2, 5 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 6 | "toAddress": "vite_a3ab3f8ce81936636af4c6f4da41612f11136d71f53bf8fa86", 7 | "data": "", 8 | "amount": "00", 9 | "tokenId": "tti_5649544520544f4b454e6e40", 10 | "pledgeBeneficialAmount": "10000000000000000000000", 11 | "err": "contract not exists", 12 | "success": false, 13 | "quota": 21000, 14 | "quotaUsed": 21000 15 | } 16 | } -------------------------------------------------------------------------------- /ledger/chain/sync_cache/writer.go: -------------------------------------------------------------------------------- 1 | package sync_cache 2 | 3 | import ( 4 | "os" 5 | ) 6 | 7 | type writer struct { 8 | cache *syncCache 9 | item *cacheItem 10 | fd *os.File 11 | } 12 | 13 | func (w *writer) Write(p []byte) (n int, err error) { 14 | return w.fd.Write(p) 15 | } 16 | 17 | func (w *writer) Close() (err error) { 18 | // close file 19 | err = w.fd.Close() 20 | if err != nil { 21 | w.cache.deleteItem(w.item) 22 | return 23 | } 24 | 25 | w.item.done = true 26 | 27 | // add item to index db 28 | err = w.cache.updateIndex(w.item) 29 | 30 | return 31 | } 32 | -------------------------------------------------------------------------------- /vm/test/interpreter_test/stop.json: -------------------------------------------------------------------------------- 1 | { 2 | "stop": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "00", 10 | "returnData": "", 11 | "quotaTotal": 100000, 12 | "quotaLeft": 100000, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000" 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /log15/handler_go14.go: -------------------------------------------------------------------------------- 1 | // +build go1.4 2 | 3 | package log15 4 | 5 | import "sync/atomic" 6 | 7 | // swapHandler wraps another handler that may be swapped out 8 | // dynamically at runtime in chain thread-safe fashion. 9 | type swapHandler struct { 10 | handler atomic.Value 11 | } 12 | 13 | func (h *swapHandler) Log(r *Record) error { 14 | return (*h.handler.Load().(*Handler)).Log(r) 15 | } 16 | 17 | func (h *swapHandler) Swap(newHandler Handler) { 18 | h.handler.Store(&newHandler) 19 | } 20 | 21 | func (h *swapHandler) Get() Handler { 22 | return *h.handler.Load().(*Handler) 23 | } 24 | -------------------------------------------------------------------------------- /contracts-vite/README.md: -------------------------------------------------------------------------------- 1 | 2 | # install && compile 3 | 4 | ``` 5 | yarn install 6 | npx hardhat compile 7 | 8 | ``` 9 | 10 | # test 11 | 12 | ``` 13 | // run a local node 14 | npx hardhat node 15 | 16 | // run the test scripts 17 | npx hardhat test test/erc20_migrator_test.js 18 | ``` 19 | 20 | # deploy to local 21 | 22 | ``` 23 | // run a local node 24 | npx hardhat node 25 | 26 | // deploy erc20 token contract 27 | npx hardhat run --network local scripts/deploy.js 28 | 29 | // deploy erc20 migrator contract 30 | npx hardhat run --network local scripts/deploy_migrator.js 31 | 32 | ``` 33 | -------------------------------------------------------------------------------- /contracts-vite/scripts/deploy_migrator.js: -------------------------------------------------------------------------------- 1 | // scripts/deploy.js 2 | async function main() { 3 | const Migrator = await ethers.getContractFactory("ViteMigrator"); 4 | console.log("Deploying Migrator ..."); 5 | const migrator = await Migrator.deploy('0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'); 6 | await migrator.deployed(); 7 | console.log("deployed to:", migrator.address); 8 | } 9 | 10 | main() 11 | .then(() => process.exit(0)) 12 | .catch(error => { 13 | console.error(error); 14 | process.exit(1); 15 | }); 16 | -------------------------------------------------------------------------------- /vm/stack_table.go: -------------------------------------------------------------------------------- 1 | package vm 2 | 3 | import "github.com/vitelabs/go-vite/v2/vm/util" 4 | 5 | func makeStackFunc(pop, push int) stackValidationFunc { 6 | return func(stack *stack) error { 7 | if err := stack.require(pop); err != nil { 8 | return err 9 | } 10 | 11 | if stack.len()+push-pop > int(stackLimit) { 12 | return util.ErrStackLimitReached 13 | } 14 | return nil 15 | } 16 | } 17 | 18 | func makeDupStackFunc(n int) stackValidationFunc { 19 | return makeStackFunc(n, n+1) 20 | } 21 | 22 | func makeSwapStackFunc(n int) stackValidationFunc { 23 | return makeStackFunc(n, n) 24 | } 25 | -------------------------------------------------------------------------------- /ledger/chain/cache/unconfirmed.go: -------------------------------------------------------------------------------- 1 | package chain_cache 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | func (cache *Cache) GetUnconfirmedBlocks() []*ledger.AccountBlock { 9 | cache.mu.RLock() 10 | defer cache.mu.RUnlock() 11 | 12 | return cache.unconfirmedPool.GetBlocks() 13 | } 14 | 15 | func (cache *Cache) GetUnconfirmedBlocksByAddress(address *types.Address) []*ledger.AccountBlock { 16 | cache.mu.RLock() 17 | defer cache.mu.RUnlock() 18 | 19 | return cache.unconfirmedPool.GetBlocksByAddress(address) 20 | } 21 | -------------------------------------------------------------------------------- /log15/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2014 Alan Shreve 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /vm/contracts/abi/util.go: -------------------------------------------------------------------------------- 1 | package abi 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces" 6 | ) 7 | 8 | // StorageDatabase define db interfaces for querying built-in contract 9 | type StorageDatabase interface { 10 | GetValue(key []byte) ([]byte, error) 11 | NewStorageIterator(prefix []byte) (interfaces.StorageIterator, error) 12 | Address() *types.Address 13 | } 14 | 15 | func filterKeyValue(key, value []byte, f func(key []byte) bool) bool { 16 | if len(value) > 0 && (f == nil || f(key)) { 17 | return true 18 | } 19 | return false 20 | } 21 | -------------------------------------------------------------------------------- /common/lock.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "sync/atomic" 5 | "time" 6 | ) 7 | 8 | type NonBlockLock struct { 9 | b int32 10 | } 11 | 12 | func (self *NonBlockLock) TryLock() bool { 13 | return atomic.CompareAndSwapInt32(&self.b, 0, 1) 14 | } 15 | 16 | func (self *NonBlockLock) Lock() { 17 | i := 0 18 | for { 19 | if atomic.CompareAndSwapInt32(&self.b, 0, 1) { 20 | return 21 | } 22 | i++ 23 | if i > 2000 { 24 | time.Sleep(time.Millisecond) 25 | i = 0 26 | } 27 | } 28 | } 29 | 30 | func (self *NonBlockLock) UnLock() bool { 31 | return atomic.CompareAndSwapInt32(&self.b, 1, 0) 32 | } 33 | -------------------------------------------------------------------------------- /contracts-vite/hardhat.config.js: -------------------------------------------------------------------------------- 1 | require("@nomiclabs/hardhat-ethers"); 2 | 3 | /** 4 | * @type import('hardhat/config').HardhatUserConfig 5 | */ 6 | module.exports = { 7 | solidity: "0.6.6", 8 | defaultNetwork: "local", 9 | networks: { 10 | hardhat: { 11 | }, 12 | local: { 13 | url: "http://127.0.0.1:8545/", 14 | accounts: ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', 15 | '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d', 16 | '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a' 17 | ] 18 | } 19 | } 20 | }; -------------------------------------------------------------------------------- /monitor/monitor_test.go: -------------------------------------------------------------------------------- 1 | package monitor 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | func TestMonitor(t *testing.T) { 9 | // record the number of times event happened 10 | LogEvent("pool", "insert") 11 | // record the time taken by sth 12 | testLogTime1() 13 | testLogTime2() 14 | // record average 15 | LogDuration("pool", "insertDuration", 2000) 16 | } 17 | 18 | func testLogTime2() { 19 | last := time.Now() 20 | time.Sleep(time.Second) 21 | LogTime("pool", "insertTime2", last) 22 | } 23 | 24 | func testLogTime1() { 25 | defer LogTime("pool", "insertTime1", time.Now()) 26 | time.Sleep(time.Second) 27 | } 28 | -------------------------------------------------------------------------------- /node/errors.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "errors" 5 | "syscall" 6 | ) 7 | 8 | var ( 9 | ErrDataDirUsed = errors.New("dataDir already used by another process") 10 | ErrNodeStopped = errors.New("node not started") 11 | ErrNodeRunning = errors.New("node already running") 12 | ErrWalletConfigNil = errors.New("wallet config is nil") 13 | datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true} 14 | ) 15 | 16 | func convertFileLockError(err error) error { 17 | if errno, ok := err.(syscall.Errno); ok && datadirInUseErrnos[uint(errno)] { 18 | return ErrDataDirUsed 19 | } 20 | return err 21 | } 22 | -------------------------------------------------------------------------------- /vm_db/storage_iterator.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/db" 5 | "github.com/vitelabs/go-vite/v2/interfaces" 6 | ) 7 | 8 | // Cannot be concurrent with write 9 | func (vdb *vmDb) NewStorageIterator(prefix []byte) (interfaces.StorageIterator, error) { 10 | iter, err := vdb.chain.GetStorageIterator(*vdb.address, prefix) 11 | if err != nil { 12 | return nil, err 13 | } 14 | 15 | unsavedIter := vdb.unsaved().NewStorageIterator(prefix) 16 | 17 | return db.NewMergedIterator([]interfaces.StorageIterator{ 18 | unsavedIter, 19 | iter, 20 | }, vdb.unsaved().IsDelete), nil 21 | } 22 | -------------------------------------------------------------------------------- /ledger/chain/cache/init.go: -------------------------------------------------------------------------------- 1 | package chain_cache 2 | 3 | func (cache *Cache) Init() error { 4 | // init latest snapshot block 5 | if err := cache.initLatestSnapshotBlock(); err != nil { 6 | return err 7 | } 8 | 9 | // init quota list 10 | if err := cache.quotaList.init(); err != nil { 11 | return err 12 | } 13 | return nil 14 | } 15 | 16 | func (cache *Cache) initLatestSnapshotBlock() error { 17 | latestSnapshotBlock, err := cache.chain.QueryLatestSnapshotBlock() 18 | if err != nil { 19 | return err 20 | } 21 | 22 | // set latest block 23 | cache.hd.SetLatestSnapshotBlock(latestSnapshotBlock) 24 | return nil 25 | } 26 | -------------------------------------------------------------------------------- /ledger/consensus/result.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | "github.com/vitelabs/go-vite/v2/ledger/consensus/core" 8 | ) 9 | 10 | type electionResult struct { 11 | Plans []*core.MemberPlan 12 | STime time.Time 13 | ETime time.Time 14 | Index uint64 15 | } 16 | 17 | func genElectionResult(info *core.GroupInfo, index uint64, members []types.Address) *electionResult { 18 | self := &electionResult{} 19 | self.STime, self.ETime = info.Index2Time(index) 20 | self.Plans = info.GenPlanByAddress(index, members) 21 | self.Index = index 22 | return self 23 | } 24 | -------------------------------------------------------------------------------- /cmd/utils/flock/flock_windows.go: -------------------------------------------------------------------------------- 1 | package flock 2 | 3 | import "syscall" 4 | 5 | type windowsLock struct { 6 | fd syscall.Handle 7 | } 8 | 9 | func (fl *windowsLock) Release() error { 10 | return syscall.Close(fl.fd) 11 | } 12 | 13 | func newLock(fileName string) (Releaser, error) { 14 | pathp, err := syscall.UTF16PtrFromString(fileName) 15 | if err != nil { 16 | return nil, err 17 | } 18 | fd, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.CREATE_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0) 19 | if err != nil { 20 | return nil, err 21 | } 22 | return &windowsLock{fd}, nil 23 | } 24 | -------------------------------------------------------------------------------- /common/config/upgrade.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/upgrade" 4 | 5 | type Upgrade struct { 6 | Level string 7 | Points map[string]*upgrade.UpgradePoint 8 | } 9 | 10 | func (cfg *Upgrade) MakeUpgradeBox() upgrade.UpgradeBox { 11 | if cfg == nil { 12 | panic("unknown upgrade nil") 13 | } 14 | if cfg.Level == "mainnet" { 15 | return upgrade.NewMainnetUpgradeBox() 16 | } else if cfg.Level == "latest" { 17 | return upgrade.NewLatestUpgradeBox() 18 | } else if cfg.Level == "custom" { 19 | return upgrade.NewCustomUpgradeBox(cfg.Points) 20 | } 21 | panic("unknown upgrade level") 22 | } 23 | -------------------------------------------------------------------------------- /ledger/pool/blacklist_test.go: -------------------------------------------------------------------------------- 1 | package pool 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/stretchr/testify/assert" 8 | 9 | "github.com/vitelabs/go-vite/v2/common" 10 | ) 11 | 12 | func TestBlacklist_AddAddTimeout(t *testing.T) { 13 | 14 | bl, err := NewBlacklist() 15 | if err != nil { 16 | assert.Fail(t, err.Error()) 17 | } 18 | hash := common.MockHash(10) 19 | bl.AddAddTimeout(hash, time.Second*5) 20 | 21 | assert.True(t, bl.Exists(hash)) 22 | 23 | time.Sleep(7 * time.Second) 24 | assert.False(t, bl.Exists(hash)) 25 | 26 | bl.AddAddTimeout(hash, time.Second*5) 27 | assert.True(t, bl.Exists(hash)) 28 | } 29 | -------------------------------------------------------------------------------- /log15/handler_go13.go: -------------------------------------------------------------------------------- 1 | // +build !go1.4 2 | 3 | package log15 4 | 5 | import ( 6 | "sync/atomic" 7 | "unsafe" 8 | ) 9 | 10 | // swapHandler wraps another handler that may be swapped out 11 | // dynamically at runtime in chain thread-safe fashion. 12 | type swapHandler struct { 13 | handler unsafe.Pointer 14 | } 15 | 16 | func (h *swapHandler) Log(r *Record) error { 17 | return h.Get().Log(r) 18 | } 19 | 20 | func (h *swapHandler) Get() Handler { 21 | return *(*Handler)(atomic.LoadPointer(&h.handler)) 22 | } 23 | 24 | func (h *swapHandler) Swap(newHandler Handler) { 25 | atomic.StorePointer(&h.handler, unsafe.Pointer(&newHandler)) 26 | } 27 | -------------------------------------------------------------------------------- /producer/worker_test.go: -------------------------------------------------------------------------------- 1 | package producer 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | 10 | "github.com/vitelabs/go-vite/v2/common/types" 11 | ) 12 | 13 | func TestStoreSeed(t *testing.T) { 14 | w := newWorker(nil, nil) 15 | 16 | hash := types.HexToHashPanic(calculateHash("100")) 17 | w.storeSeedHash(100, &hash) 18 | result := w.getSeedByHash(&hash) 19 | assert.Equal(t, uint64(100), result) 20 | } 21 | 22 | func calculateHash(s string) string { 23 | h := sha256.New() 24 | h.Write([]byte(s)) 25 | hashed := h.Sum(nil) 26 | return hex.EncodeToString(hashed) 27 | } 28 | -------------------------------------------------------------------------------- /wallet/hd-bip/derivation/bip_main_test.go: -------------------------------------------------------------------------------- 1 | package derivation 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestExampleMnemonic12(t *testing.T) { 8 | if err := RandomMnemonic12(""); err != nil { 9 | t.Fatal(err) 10 | } 11 | 12 | if err := RandomMnemonic12("123456"); err != nil { 13 | t.Fatal(err) 14 | } 15 | 16 | var b [16]byte 17 | if err := Menmonic(b[:], ""); err != nil { 18 | t.Fatal(err) 19 | } 20 | } 21 | 22 | func TestExampleMnemonic24(t *testing.T) { 23 | if err := RandomMnemonic24(""); err != nil { 24 | t.Fatal(err) 25 | } 26 | 27 | if err := RandomMnemonic24("123456"); err != nil { 28 | t.Fatal(err) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /log15/term/terminal_notwindows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by chain BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build linux,!appengine darwin freebsd openbsd netbsd 7 | 8 | package term 9 | 10 | import ( 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | // IsTty returns true if the given file descriptor is chain terminal. 16 | func IsTty(fd uintptr) bool { 17 | var termios Termios 18 | _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) 19 | return err == 0 20 | } 21 | -------------------------------------------------------------------------------- /ledger/onroad/reader.go: -------------------------------------------------------------------------------- 1 | package onroad 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces" 6 | "github.com/vitelabs/go-vite/v2/net" 7 | "github.com/vitelabs/go-vite/v2/producer/producerevent" 8 | ) 9 | 10 | type pool interface { 11 | AddDirectAccountBlock(address types.Address, vmAccountBlock *interfaces.VmAccountBlock) error 12 | } 13 | 14 | type producer interface { 15 | SetAccountEventFunc(func(producerevent.AccountEvent)) 16 | } 17 | 18 | type netReader interface { 19 | SubscribeSyncStatus(fn func(net.SyncState)) (subId int) 20 | UnsubscribeSyncStatus(subId int) 21 | SyncState() net.SyncState 22 | } 23 | -------------------------------------------------------------------------------- /net/sync_state_test.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func ExampleSyncState_MarshalText() { 9 | var s SyncState 10 | 11 | data, err := s.MarshalText() 12 | if err != nil { 13 | panic(err) 14 | } 15 | 16 | fmt.Printf("%s\n", data) 17 | // Output: 18 | // Sync Not Start 19 | } 20 | 21 | func TestSyncState_MarshalText(t *testing.T) { 22 | var s SyncState 23 | 24 | data, err := s.MarshalText() 25 | if err != nil { 26 | panic(err) 27 | } 28 | 29 | var s2 = new(SyncState) 30 | err = s2.UnmarshalText(data) 31 | if err != nil { 32 | panic(err) 33 | } 34 | 35 | if *s2 != s { 36 | t.Error("wrong state", *s2) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /ledger/chain/block/account_block.go: -------------------------------------------------------------------------------- 1 | package chain_block 2 | 3 | import ( 4 | "fmt" 5 | 6 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 7 | chain_file_manager "github.com/vitelabs/go-vite/v2/ledger/chain/file_manager" 8 | ) 9 | 10 | // GetAccountBlock by location 11 | func (bDB *BlockDB) GetAccountBlock(location *chain_file_manager.Location) (*ledger.AccountBlock, error) { 12 | buf, err := bDB.Read(location) 13 | if err != nil { 14 | return nil, err 15 | } 16 | 17 | ab := &ledger.AccountBlock{} 18 | if err := ab.Deserialize(buf); err != nil { 19 | return nil, fmt.Errorf("ab.Deserialize failed, [Error] %s", err.Error()) 20 | } 21 | 22 | return ab, nil 23 | } 24 | -------------------------------------------------------------------------------- /vm/test/interpreter_test/codesize.json: -------------------------------------------------------------------------------- 1 | { 2 | "codesize": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "38600055", 10 | "returnData": "", 11 | "quotaTotal": 100000000000, 12 | "quotaLeft": 99999979995, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000", 16 | "0000000000000000000000000000000000000000000000000000000000000000": "04" 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /common/condTimeout_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestCondTimeout(t *testing.T) { 10 | cd := NewTimeoutCond() 11 | 12 | for i := 0; i < 10; i++ { 13 | go func(i int) { 14 | fmt.Printf("wait for %d\n", i) 15 | defer fmt.Printf("wait for %d end\n", i) 16 | cd.Wait() 17 | }(i) 18 | } 19 | 20 | for i := 0; i < 5; i++ { 21 | go func(i int) { 22 | fmt.Printf("wait timeout for %d, %d\n", i, time.Now().Second()) 23 | cd.WaitTimeout(time.Second * 2) 24 | fmt.Printf("wait timeout for %d end,%d \n", i, time.Now().Second()) 25 | }(i) 26 | } 27 | 28 | time.Sleep(time.Second * 5) 29 | cd.Broadcast() 30 | 31 | } 32 | -------------------------------------------------------------------------------- /common/db/xleveldb/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014, Suryandaru Triandana 2 | // All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license that can be 5 | // found in the LICENSE file. 6 | 7 | package leveldb 8 | 9 | import ( 10 | "github.com/vitelabs/go-vite/v2/common/db/xleveldb/errors" 11 | ) 12 | 13 | // Common errors. 14 | var ( 15 | ErrNotFound = errors.ErrNotFound 16 | ErrReadOnly = errors.New("leveldb: read-only mode") 17 | ErrSnapshotReleased = errors.New("leveldb: snapshot released") 18 | ErrIterReleased = errors.New("leveldb: iterator released") 19 | ErrClosed = errors.New("leveldb: closed") 20 | ) 21 | -------------------------------------------------------------------------------- /ledger/chain/genesis/interface.go: -------------------------------------------------------------------------------- 1 | package chain_genesis 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces" 6 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 7 | ) 8 | 9 | type Chain interface { 10 | InsertSnapshotBlock(snapshotBlock *ledger.SnapshotBlock) (invalidAccountBlocks []*ledger.AccountBlock, err error) 11 | InsertAccountBlock(vmAccountBlocks *interfaces.VmAccountBlock) error 12 | QuerySnapshotBlockByHeight(uint64) (*ledger.SnapshotBlock, error) 13 | GetContentNeedSnapshot() ledger.SnapshotContent 14 | 15 | WriteGenesisCheckSum(hash types.Hash) error 16 | QueryGenesisCheckSum() (*types.Hash, error) 17 | } 18 | -------------------------------------------------------------------------------- /vm/test/interpreter_test/arith.json: -------------------------------------------------------------------------------- 1 | { 2 | "arith1": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "6001600190016007026005016002900460049060016021900560150160030260059007600303600960110a60005260086000f3", 10 | "returnData": "0000000000000000", 11 | "quotaTotal": 1000000, 12 | "quotaLeft": 999831, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000" 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /vm/test/interpreter_test/callvalue.json: -------------------------------------------------------------------------------- 1 | { 2 | "callvalue": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "34600055", 10 | "returnData": "", 11 | "quotaTotal": 100000000000, 12 | "quotaLeft": 99999979995, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000", 16 | "0000000000000000000000000000000000000000000000000000000000000000": "0de0b6b3a7640000" 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /common/condTimer_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestCondTimer(t *testing.T) { 10 | cd := NewCondTimer() 11 | 12 | for i := 0; i < 10; i++ { 13 | go func(i int) { 14 | fmt.Printf("wait for %d\n", i) 15 | defer fmt.Printf("wait for %d end\n", i) 16 | cd.Wait() 17 | }(i) 18 | } 19 | 20 | for i := 0; i < 5; i++ { 21 | go func(i int) { 22 | fmt.Printf("wait timeout for %d, %d\n", i, time.Now().Second()) 23 | cd.Wait() 24 | fmt.Printf("wait timeout for %d end,%d \n", i, time.Now().Second()) 25 | }(i) 26 | } 27 | 28 | cd.Start(time.Second) 29 | time.Sleep(time.Second * 5) 30 | cd.Broadcast() 31 | defer cd.Stop() 32 | 33 | } 34 | -------------------------------------------------------------------------------- /vm/test/interpreter_test/balance.json: -------------------------------------------------------------------------------- 1 | { 2 | "self_balance": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "692445f6e5cde8c2c70e4431600055", 10 | "returnData": "", 11 | "quotaTotal": 100000, 12 | "quotaLeft": 79594, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000", 16 | "0000000000000000000000000000000000000000000000000000000000000000": "0de0b6b3a7640000" 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /wallet/hd-bip/main/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/vitelabs/go-vite/v2/wallet/hd-bip/derivation" 7 | ) 8 | 9 | func main() { 10 | //if err := derivation.RandomMnemonic12(""); err != nil { 11 | // fmt.Println(err) 12 | //} 13 | // 14 | //if err := derivation.RandomMnemonic12("123456"); err != nil { 15 | // fmt.Println(err) 16 | //} 17 | // 18 | //var b [16]byte 19 | //if err := derivation.Menmonic(b[:],""); err != nil { 20 | // fmt.Println(err) 21 | //} 22 | 23 | if err := derivation.RandomMnemonic24(""); err != nil { 24 | fmt.Println(err) 25 | } 26 | 27 | //if err := derivation.RandomMnemonic24("123456"); err != nil { 28 | // fmt.Println(err) 29 | //} 30 | 31 | } 32 | -------------------------------------------------------------------------------- /interfaces/wallet.go: -------------------------------------------------------------------------------- 1 | package interfaces 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/crypto/ed25519" 6 | ) 7 | 8 | // SignFunc is the function type defining the callback when a block requires a 9 | // method to sign the transaction in generator. 10 | type SignFunc func(msg []byte) (signedData []byte, pub ed25519.PublicKey, err error) 11 | 12 | // VerifyFunc is the function 13 | type VerifyFunc func(pub ed25519.PublicKey, message, signdata []byte) error 14 | 15 | type Account interface { 16 | Address() types.Address 17 | Sign(msg []byte) (signData []byte, pub ed25519.PublicKey, err error) 18 | Verify(pub ed25519.PublicKey, message, signdata []byte) error 19 | } 20 | -------------------------------------------------------------------------------- /common/goroutine.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/pkg/errors" 7 | 8 | "github.com/vitelabs/go-vite/v2/log15" 9 | ) 10 | 11 | var glog = log15.New("module", "error") 12 | 13 | func Go(fn func()) { 14 | go wrap(fn) 15 | } 16 | 17 | func wrap(fn func()) { 18 | defer catch() 19 | fn() 20 | } 21 | 22 | func catch() { 23 | if err := recover(); err != nil { 24 | var e error 25 | switch t := err.(type) { 26 | case error: 27 | e = errors.WithStack(t) 28 | case string: 29 | e = errors.New(t) 30 | default: 31 | e = errors.Errorf("unknown type %+v", err) 32 | } 33 | 34 | glog.Error("panic", "err", err, "withstack", e) 35 | fmt.Printf("%+v", e) 36 | panic(err) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /vm/test/interpreter_test/address.json: -------------------------------------------------------------------------------- 1 | { 2 | "address0": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "30600055", 10 | "returnData": "", 11 | "quotaTotal": 100000000000, 12 | "quotaLeft": 99999979995, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000", 16 | "0000000000000000000000000000000000000000000000000000000000000000": "470328ad08903a431953bfdcaf7760c084233c4700" 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /vm/test/interpreter_test/caller.json: -------------------------------------------------------------------------------- 1 | { 2 | "caller": { 3 | "sBHeight": 1, 4 | "fromAddress": "vite_ab24ef68b84e642c0ddca06beec81c9acb1977bbd7da27a87a", 5 | "toAddress": "vite_470328ad08903a431953bfdcaf7760c084233c475e5726a35c", 6 | "inputData": "", 7 | "amount": "0de0b6b3a7640000", 8 | "tokenID": "tti_2445f6e5cde8c2c70e446c83", 9 | "code": "33600055", 10 | "returnData": "", 11 | "quotaTotal": 100000000000, 12 | "quotaLeft": 99999979995, 13 | "err": "", 14 | "storage": { 15 | "$BALANCEtti_2445f6e5cde8c2c70e446c83": "0de0b6b3a7640000", 16 | "0000000000000000000000000000000000000000000000000000000000000000": "ab24ef68b84e642c0ddca06beec81c9acb1977bb00" 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /bin/ubuntu/upgrade_tar_gz.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | version="$1" 5 | 6 | if [ -z "$version" ]; then 7 | echo "error: upgrade_tar_gz.sh [version]" 8 | exit 1 9 | fi 10 | 11 | wget -c https://github.com/vitelabs/go-vite/releases/download/${version}/gvite-${version}-linux.tar.gz 12 | 13 | tar xvf gvite-${version}-linux.tar.gz 14 | 15 | echo "gvite backup." 16 | 17 | sudo mv /usr/local/vite/gvite /usr/local/vite/gvite_`date "+%Y_%m_%d"` 2>/dev/null 18 | 19 | echo "replace new version gvite" 20 | sudo cp gvite-${version}-linux/gvite /usr/local/vite 21 | 22 | echo "replace finished." 23 | 24 | echo "restart gvite" 25 | 26 | sudo service vite restart 27 | 28 | echo "restart done" 29 | 30 | /usr/local/vite/gvite version 31 | -------------------------------------------------------------------------------- /vm_db/storage.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import "github.com/pkg/errors" 4 | 5 | func (vdb *vmDb) GetValue(key []byte) ([]byte, error) { 6 | if value, ok := vdb.unsaved().GetValue(key); ok { 7 | return value, nil 8 | } 9 | return vdb.GetOriginalValue(key) 10 | } 11 | func (vdb *vmDb) GetOriginalValue(key []byte) ([]byte, error) { 12 | return vdb.chain.GetValue(*vdb.address, key) 13 | } 14 | 15 | func (vdb *vmDb) SetValue(key []byte, value []byte) error { 16 | if len(key) > 32 { 17 | return errors.New("the length of key is not allowed to exceed 32 bytes") 18 | } 19 | vdb.unsaved().SetValue(key, value) 20 | return nil 21 | } 22 | 23 | func (vdb *vmDb) GetUnsavedStorage() [][2][]byte { 24 | return vdb.unsaved().GetStorage() 25 | } 26 | -------------------------------------------------------------------------------- /ledger/chain/plugins/db_key_prefix.go: -------------------------------------------------------------------------------- 1 | package chain_plugins 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | const ( 6 | OnRoadInfoKeyPrefix = byte(1) 7 | 8 | DiffTokenHash = byte(2) 9 | ) 10 | 11 | func CreateOnRoadInfoKey(addr *types.Address, tId *types.TokenTypeId) []byte { 12 | key := make([]byte, 0, 1+types.AddressSize+types.TokenTypeIdSize) 13 | key = append(key, OnRoadInfoKeyPrefix) 14 | key = append(key, addr.Bytes()...) 15 | key = append(key, tId.Bytes()...) 16 | return key 17 | } 18 | 19 | func CreateOnRoadInfoPrefixKey(addr *types.Address) []byte { 20 | key := make([]byte, 0, 1+types.AddressSize) 21 | key = append(key, OnRoadInfoKeyPrefix) 22 | key = append(key, addr.Bytes()...) 23 | return key 24 | } 25 | -------------------------------------------------------------------------------- /log15/term/terminal_windows.go: -------------------------------------------------------------------------------- 1 | // Based on ssh/terminal: 2 | // Copyright 2011 The Go Authors. All rights reserved. 3 | // Use of this source code is governed by chain BSD-style 4 | // license that can be found in the LICENSE file. 5 | 6 | // +build windows 7 | 8 | package term 9 | 10 | import ( 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | var kernel32 = syscall.NewLazyDLL("kernel32.dll") 16 | 17 | var ( 18 | procGetConsoleMode = kernel32.NewProc("GetConsoleMode") 19 | ) 20 | 21 | // IsTty returns true if the given file descriptor is chain terminal. 22 | func IsTty(fd uintptr) bool { 23 | var st uint32 24 | r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) 25 | return r != 0 && e == 0 26 | } 27 | -------------------------------------------------------------------------------- /net/vnode/mode.go: -------------------------------------------------------------------------------- 1 | package vnode 2 | 3 | // NodeMode mean the level of a node in the current hierarchy 4 | // Core nodes works on the highest level, usually are producers 5 | // Relay nodes usually are the standby producers, and partial full nodes (like static nodes) 6 | // Regular nodes usually are the full nodes 7 | // Edge nodes usually are the light nodes 8 | type NodeMode byte 9 | 10 | const ( 11 | Edge NodeMode = 1 << iota 12 | Regular 13 | Relay 14 | Core 15 | ) 16 | 17 | func (n NodeMode) String() string { 18 | switch n { 19 | case Edge: 20 | return "edge" 21 | case Regular: 22 | return "regular" 23 | case Relay: 24 | return "relay" 25 | case Core: 26 | return "core" 27 | default: 28 | return "unknown" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ledger/chain/sync_cache/segment_test.go: -------------------------------------------------------------------------------- 1 | package sync_cache 2 | 3 | import "testing" 4 | 5 | func TestNewSegmentByFilename(t *testing.T) { 6 | name := "f_100_0000000000000000000000000000000000000000000000000000000000000001_200_0000000000000000000000000000000000000000000000000000000000000002" 7 | seg, err := newSegmentByFilename(name) 8 | if err != nil { 9 | t.Error(err) 10 | } 11 | if seg.From != 100 || seg.To != 200 { 12 | t.Errorf("different bound: %d %d", seg.From, seg.To) 13 | } 14 | 15 | name = "f_100_0000000000000000000000000000000000000000000000000000000000000001_200_0000000000000000000000000000000000000000000000000000000000000002.v" 16 | seg, err = newSegmentByFilename(name) 17 | if err != nil { 18 | t.Error(err) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /rpcapi/api/health.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/vitelabs/go-vite/v2" 7 | "github.com/vitelabs/go-vite/v2/common/db/xleveldb/errors" 8 | ) 9 | 10 | const InvalidSnapshotMinutes = 3 11 | 12 | type Health struct { 13 | vite *vite.Vite 14 | } 15 | 16 | func NewHealthApi(vite *vite.Vite) *Health { 17 | return &Health{vite: vite} 18 | } 19 | 20 | func (h *Health) Health() error { 21 | sb := h.vite.Chain().GetLatestSnapshotBlock() 22 | if sb == nil { 23 | return errors.New("check node height failed, sb nil") 24 | } 25 | nowTime := time.Now() 26 | if nowTime.After(sb.Timestamp.Add(InvalidSnapshotMinutes * time.Minute)) { 27 | return errors.New("check node height failed, height invalid") 28 | } 29 | return nil 30 | } 31 | -------------------------------------------------------------------------------- /net/vnode/host_test.go: -------------------------------------------------------------------------------- 1 | package vnode 2 | 3 | import "fmt" 4 | 5 | func ExampleHostType_Is() { 6 | fmt.Println(HostIPv4.Is(HostIPv4)) 7 | fmt.Println(HostIPv6.Is(HostIPv6)) 8 | fmt.Println(HostIP.Is(HostIP)) 9 | fmt.Println(HostDomain.Is(HostDomain)) 10 | fmt.Println(HostIPv4.Is(HostIP)) 11 | fmt.Println(HostIPv6.Is(HostIP)) 12 | fmt.Println(HostIPv4.Is(HostIPv6)) 13 | fmt.Println(HostIPv6.Is(HostIPv4)) 14 | fmt.Println(HostIPv4.Is(HostDomain)) 15 | fmt.Println(HostIPv6.Is(HostDomain)) 16 | fmt.Println(HostDomain.Is(HostIP)) 17 | fmt.Println(HostIP.Is(HostDomain)) 18 | // Output: 19 | // true 20 | // true 21 | // true 22 | // true 23 | // true 24 | // true 25 | // false 26 | // false 27 | // false 28 | // false 29 | // false 30 | // false 31 | } 32 | -------------------------------------------------------------------------------- /wallet/account_test.go: -------------------------------------------------------------------------------- 1 | package wallet 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestAccount(t *testing.T) { 10 | acc, err := RandomAccount() 11 | if err != nil { 12 | t.Error(err) 13 | t.FailNow() 14 | } 15 | 16 | msg := []byte("hello world") 17 | sig, pub, err := acc.Sign(msg) 18 | if err != nil { 19 | t.Error(err) 20 | t.FailNow() 21 | } 22 | err = acc.Verify(pub, msg, sig) 23 | if err != nil { 24 | t.Error(err) 25 | t.FailNow() 26 | } 27 | 28 | acc2, err := NewAccountFromHexKey(acc.priv.Hex()) 29 | if err != nil { 30 | t.Error(err) 31 | t.FailNow() 32 | } 33 | 34 | assert.Equal(t, acc.priv.Hex(), acc2.priv.Hex()) 35 | assert.Equal(t, acc.address.Hex(), acc2.address.Hex()) 36 | } 37 | -------------------------------------------------------------------------------- /vm_db/snapshot_block.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | func (vdb *vmDb) GetGenesisSnapshotBlock() *ledger.SnapshotBlock { 9 | return vdb.chain.GetGenesisSnapshotBlock() 10 | } 11 | 12 | func (db *vmDb) GetConfirmSnapshotHeader(blockHash types.Hash) (*ledger.SnapshotBlock, error) { 13 | return db.chain.GetConfirmSnapshotHeaderByAbHash(blockHash) 14 | } 15 | 16 | func (db *vmDb) GetConfirmedTimes(blockHash types.Hash) (uint64, error) { 17 | return db.chain.GetConfirmedTimes(blockHash) 18 | } 19 | 20 | func (db *vmDb) GetSnapshotBlockByHeight(height uint64) (*ledger.SnapshotBlock, error) { 21 | return db.chain.GetSnapshotBlockByHeight(height) 22 | } 23 | -------------------------------------------------------------------------------- /ledger/chain/cache/quota.go: -------------------------------------------------------------------------------- 1 | package chain_cache 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | func (cache *Cache) GetQuotaUsedList(addr types.Address) []types.QuotaInfo { 9 | cache.mu.RLock() 10 | defer cache.mu.RUnlock() 11 | 12 | return cache.quotaList.GetQuotaUsedList(addr) 13 | } 14 | 15 | func (cache *Cache) GetGlobalQuota() types.QuotaInfo { 16 | cache.mu.RLock() 17 | defer cache.mu.RUnlock() 18 | 19 | return cache.quotaList.GetGlobalQuota() 20 | } 21 | 22 | func (cache *Cache) ResetUnconfirmedQuotas(unconfirmedBlocks []*ledger.AccountBlock) { 23 | cache.mu.Lock() 24 | defer cache.mu.Unlock() 25 | 26 | cache.quotaList.ResetUnconfirmedQuotas(unconfirmedBlocks) 27 | } 28 | -------------------------------------------------------------------------------- /common/utils.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "sync" 7 | "time" 8 | 9 | "github.com/vitelabs/go-vite/v2/log15" 10 | ) 11 | 12 | func SyncMapLen(m *sync.Map) uint64 { 13 | if m == nil { 14 | return 0 15 | } 16 | i := uint64(0) 17 | m.Range(func(key, value interface{}) bool { 18 | i++ 19 | return true 20 | }) 21 | return i 22 | } 23 | 24 | func ToJson(item interface{}) string { 25 | byt, err := json.Marshal(item) 26 | if err != nil { 27 | return "err: " + err.Error() 28 | } 29 | return string(byt) 30 | } 31 | 32 | func Crit(msg string, ctx ...interface{}) { 33 | log := log15.New("moduble", "crit") 34 | log.Error(msg, ctx...) 35 | fmt.Printf("%s\n", msg) 36 | time.Sleep(time.Second * 2) 37 | log.Crit(msg, ctx...) 38 | } 39 | -------------------------------------------------------------------------------- /ledger/pipeline/pipeline_blocks_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestPipeline(t *testing.T) { 11 | prepareTestData(t, tmpDir) 12 | 13 | pipeline, err := newBlocksPipelineWithRun(tmpDir, 400, testFilesize) 14 | if err != nil { 15 | t.Error(err) 16 | t.FailNow() 17 | } 18 | time.Sleep(time.Second) 19 | 20 | chunk1 := pipeline.Peek() 21 | chunk2 := pipeline.Peek() 22 | assert.Equal(t, len(chunk1.SnapshotChunks), len(chunk2.SnapshotChunks)) 23 | assert.Equal(t, chunk1.SnapshotRange[0].Height, chunk2.SnapshotRange[0].Height) 24 | assert.Equal(t, chunk1.SnapshotRange[1].Height, chunk2.SnapshotRange[1].Height) 25 | t.Log(chunk1.SnapshotRange[0].Height, chunk1.SnapshotRange[1].Height) 26 | } 27 | -------------------------------------------------------------------------------- /vm/params.go: -------------------------------------------------------------------------------- 1 | package vm 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/helper" 7 | "github.com/vitelabs/go-vite/v2/vm/util" 8 | ) 9 | 10 | const ( 11 | callDepth uint16 = 512 // Maximum Depth of call. 12 | stackLimit uint64 = 1024 // Maximum size of VM stack allowed. 13 | 14 | maxCodeSize int = 24575 // Maximum bytecode to permit for a contract 15 | offChainReaderGas uint64 = 1000000 16 | 17 | snapshotCountMin uint8 = 0 18 | snapshotCountMax uint8 = 75 19 | snapshotWithSeedCountMin uint8 = 0 20 | snapshotWithSeedCountMax uint8 = 75 21 | 22 | contractModifyStorageMax int = 100 23 | 24 | retry = true 25 | noRetry = false 26 | ) 27 | 28 | var ( 29 | createContractFee = new(big.Int).Mul(helper.Big10, util.AttovPerVite) 30 | ) 31 | -------------------------------------------------------------------------------- /vm_db/balance.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | func (vdb *vmDb) GetBalance(tokenTypeId *types.TokenTypeId) (*big.Int, error) { 10 | if vdb.uns != nil { 11 | if balance, ok := vdb.unsaved().GetBalance(tokenTypeId); ok { 12 | return new(big.Int).Set(balance), nil 13 | } 14 | } 15 | 16 | return vdb.chain.GetBalance(*vdb.address, *tokenTypeId) 17 | } 18 | 19 | func (vdb *vmDb) SetBalance(tokenTypeId *types.TokenTypeId, amount *big.Int) { 20 | vdb.unsaved().SetBalance(tokenTypeId, amount) 21 | } 22 | 23 | func (vdb *vmDb) GetUnsavedBalanceMap() map[types.TokenTypeId]*big.Int { 24 | if vdb.uns == nil { 25 | return make(map[types.TokenTypeId]*big.Int) 26 | } 27 | return vdb.unsaved().GetBalanceMap() 28 | } 29 | -------------------------------------------------------------------------------- /cmd/printer/index/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/helper" 8 | "github.com/vitelabs/go-vite/v2/common/types" 9 | chain_index "github.com/vitelabs/go-vite/v2/ledger/chain/index" 10 | ) 11 | 12 | // env GOOS=linux GOARCH=amd64 go build -i -o index_printer ./cmd/printer/index/main.go 13 | 14 | var hash = flag.String("hash", "", "hash") 15 | var dir = flag.String("dataDir", "devdata", "data dir, for example: devdata") 16 | 17 | func main() { 18 | flag.Parse() 19 | db, err := chain_index.NewIndexDB(*dir) 20 | 21 | helper.AssertNil(err) 22 | hash := types.HexToHashPanic(*hash) 23 | location, err := db.GetAccountBlockLocationByHash(&hash) 24 | helper.AssertNil(err) 25 | fmt.Println("location", location.FileId, location.Offset) 26 | } 27 | -------------------------------------------------------------------------------- /cmd/utils/flock/flock_darwin.go: -------------------------------------------------------------------------------- 1 | package flock 2 | 3 | import ( 4 | "os" 5 | "syscall" 6 | ) 7 | 8 | type unixLock struct { 9 | f *os.File 10 | } 11 | 12 | func (l *unixLock) Release() error { 13 | if err := l.set(false); err != nil { 14 | return err 15 | } 16 | return l.f.Close() 17 | } 18 | 19 | func (l *unixLock) set(lock bool) error { 20 | how := syscall.LOCK_UN 21 | if lock { 22 | how = syscall.LOCK_EX 23 | } 24 | return syscall.Flock(int(l.f.Fd()), how|syscall.LOCK_NB) 25 | } 26 | 27 | func newLock(fileName string) (Releaser, error) { 28 | f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) 29 | if err != nil { 30 | return nil, err 31 | } 32 | l := &unixLock{f} 33 | err = l.set(true) 34 | if err != nil { 35 | f.Close() 36 | return nil, err 37 | } 38 | return l, nil 39 | } 40 | -------------------------------------------------------------------------------- /cmd/utils/flock/flock_linux.go: -------------------------------------------------------------------------------- 1 | package flock 2 | 3 | import ( 4 | "os" 5 | "syscall" 6 | ) 7 | 8 | type unixLock struct { 9 | f *os.File 10 | } 11 | 12 | func (l *unixLock) Release() error { 13 | if err := l.set(false); err != nil { 14 | return err 15 | } 16 | return l.f.Close() 17 | } 18 | 19 | func (l *unixLock) set(lock bool) error { 20 | how := syscall.LOCK_UN 21 | if lock { 22 | how = syscall.LOCK_EX 23 | } 24 | return syscall.Flock(int(l.f.Fd()), how|syscall.LOCK_NB) 25 | } 26 | 27 | func newLock(fileName string) (Releaser, error) { 28 | f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) 29 | if err != nil { 30 | return nil, err 31 | } 32 | l := &unixLock{f} 33 | err = l.set(true) 34 | if err != nil { 35 | f.Close() 36 | return nil, err 37 | } 38 | return l, nil 39 | } 40 | -------------------------------------------------------------------------------- /ledger/verifier/reader.go: -------------------------------------------------------------------------------- 1 | package verifier 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | "github.com/vitelabs/go-vite/v2/vm_db" 7 | ) 8 | 9 | type cssConsensus interface { 10 | VerifyAccountProducer(block *ledger.AccountBlock) (bool, error) 11 | } 12 | 13 | type onRoadPool interface { 14 | IsFrontOnRoadOfCaller(gid types.Gid, orAddr, caller types.Address, hash types.Hash) (bool, error) 15 | } 16 | 17 | type accountChain interface { 18 | vm_db.Chain 19 | 20 | IsReceived(sendBlockHash types.Hash) (bool, error) 21 | GetReceiveAbBySendAb(sendBlockHash types.Hash) (*ledger.AccountBlock, error) 22 | IsGenesisAccountBlock(block types.Hash) bool 23 | IsSeedConfirmedNTimes(blockHash types.Hash, n uint64) (bool, error) 24 | } 25 | -------------------------------------------------------------------------------- /monitor/ring_test.go: -------------------------------------------------------------------------------- 1 | package monitor 2 | 3 | import "testing" 4 | 5 | func TestRing(t *testing.T) { 6 | r := newRing(10) 7 | 8 | r.add(0) 9 | r.add(1) 10 | r.add(2) 11 | all := r.all() 12 | if len(all) != 3 { 13 | t.Error("error len.") 14 | } 15 | for _, v := range all { 16 | println(v.(int)) 17 | } 18 | 19 | r.reset() 20 | 21 | all = r.all() 22 | 23 | if len(all) != 0 { 24 | t.Error("error len.") 25 | } 26 | 27 | r.add(10) 28 | r.add(11) 29 | 30 | for _, v := range r.all() { 31 | println(v.(int)) 32 | } 33 | 34 | println("------------------") 35 | r.reset() 36 | for i := 0; i < 12; i++ { 37 | r.add(i) 38 | } 39 | 40 | all = r.all() 41 | if len(all) != 10 { 42 | t.Error("error len.") 43 | } 44 | 45 | for _, v := range all { 46 | println(v.(int)) 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /vm/contracts/dex/utils_test.go: -------------------------------------------------------------------------------- 1 | package dex 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestDeComposeOrderId(t *testing.T) { 11 | orderByt, err := hex.DecodeString("00000300ffffffff4fed5fa0dfff005d94f2bd000014") 12 | if err != nil { 13 | t.Error(err) 14 | t.FailNow() 15 | } 16 | 17 | marketId, side, price, timestamp, err := DeComposeOrderId(orderByt) 18 | if err != nil { 19 | t.Error(err) 20 | t.FailNow() 21 | } 22 | t.Log(marketId, side, BytesToPrice(price), timestamp) 23 | 24 | assert.Equal(t, marketId, int32(3), "assert market") 25 | assert.Equal(t, side, false, "assert side") 26 | assert.Equal(t, BytesToPrice(price), "176.08", "assert price") 27 | assert.Equal(t, timestamp, int64(1570042557), "assert timestamp") 28 | } 29 | -------------------------------------------------------------------------------- /common/db/xleveldb/storage/file_storage_nacl.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, Suryandaru Triandana 2 | // All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license that can be 5 | // found in the LICENSE file. 6 | 7 | // +build nacl 8 | 9 | package storage 10 | 11 | import ( 12 | "os" 13 | "syscall" 14 | ) 15 | 16 | func newFileLock(path string, readOnly bool) (fl fileLock, err error) { 17 | return nil, syscall.ENOTSUP 18 | } 19 | 20 | func setFileLock(f *os.File, readOnly, lock bool) error { 21 | return syscall.ENOTSUP 22 | } 23 | 24 | func rename(oldpath, newpath string) error { 25 | return syscall.ENOTSUP 26 | } 27 | 28 | func isErrInvalid(err error) bool { 29 | return false 30 | } 31 | 32 | func syncDir(name string) error { 33 | return syscall.ENOTSUP 34 | } 35 | -------------------------------------------------------------------------------- /common/log.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "io" 5 | "path/filepath" 6 | 7 | "gopkg.in/natefinch/lumberjack.v2" 8 | 9 | "github.com/vitelabs/go-vite/v2/log15" 10 | ) 11 | 12 | func makeDefaultLogger(absFilePath string) io.Writer { 13 | return &lumberjack.Logger{ 14 | Filename: absFilePath, 15 | MaxSize: 100, 16 | MaxBackups: 14, 17 | MaxAge: 14, 18 | Compress: true, 19 | LocalTime: true, 20 | } 21 | } 22 | 23 | func LogHandler(path, subDir, filename, lvl string) log15.Handler { 24 | logLevel, err := log15.LvlFromString(lvl) 25 | if err != nil { 26 | logLevel = log15.LvlInfo 27 | } 28 | absFilename := filepath.Join(path, subDir, filename) 29 | out := makeDefaultLogger(absFilename) 30 | return log15.LvlFilterHandler(logLevel, log15.StreamHandler(out, log15.LogfmtFormat())) 31 | } 32 | -------------------------------------------------------------------------------- /vm/gas_table_test.go: -------------------------------------------------------------------------------- 1 | package vm 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/helper" 7 | "github.com/vitelabs/go-vite/v2/vm/util" 8 | ) 9 | 10 | func TestMemoryGasCost(t *testing.T) { 11 | initEmptyFork(t) 12 | 13 | vm := &VM{gasTable: util.QuotaTableByHeight(1)} 14 | size := uint64(0xffffffffe0) 15 | v, _, err := memoryGasCost(vm, &memory{}, size) 16 | if err != nil { 17 | t.Error("didn't expect error:", err) 18 | } 19 | if v != 36028899963961341 { 20 | t.Errorf("Expected: 36028899963961341, got %d", v) 21 | } 22 | 23 | _, _, err = memoryGasCost(vm, &memory{}, size+1) 24 | if err == nil { 25 | t.Error("expected error") 26 | } 27 | 28 | _, _, err = memoryGasCost(vm, &memory{}, helper.MaxUint64-64) 29 | if err == nil { 30 | t.Errorf("Expected error") 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /crypto/hash.go: -------------------------------------------------------------------------------- 1 | package crypto 2 | 3 | import ( 4 | "golang.org/x/crypto/blake2b" 5 | "golang.org/x/crypto/sha3" 6 | ) 7 | 8 | func Hash256(data ...[]byte) []byte { 9 | d, _ := blake2b.New256(nil) 10 | for _, item := range data { 11 | d.Write(item) 12 | } 13 | return d.Sum(nil) 14 | } 15 | 16 | func Keccak256(data ...[]byte) []byte { 17 | d := sha3.NewLegacyKeccak256() 18 | for _, item := range data { 19 | d.Write(item) 20 | } 21 | return d.Sum(nil) 22 | } 23 | 24 | func Hash512(data ...[]byte) []byte { 25 | d, _ := blake2b.New512(nil) 26 | for _, item := range data { 27 | d.Write(item) 28 | } 29 | return d.Sum(nil) 30 | } 31 | 32 | func Hash(size int, data ...[]byte) []byte { 33 | d, _ := blake2b.New(size, nil) 34 | for _, item := range data { 35 | d.Write(item) 36 | } 37 | return d.Sum(nil) 38 | } 39 | -------------------------------------------------------------------------------- /net/discovery/protos/message.proto: -------------------------------------------------------------------------------- 1 | syntax="proto3"; 2 | 3 | package protos; 4 | 5 | message node { 6 | bytes id = 1; 7 | bytes endpoint = 2; 8 | uint32 net = 3; 9 | bytes ext = 4; 10 | 11 | int64 activeAt = 5; 12 | int64 checkAt = 6; 13 | } 14 | 15 | message ping { 16 | bytes from = 1; 17 | bytes to = 2; 18 | uint32 net = 3; 19 | bytes ext = 4; 20 | int64 time = 5; 21 | } 22 | 23 | message pong { 24 | bytes from = 1; 25 | bytes to = 2; 26 | bytes echo = 3; 27 | uint32 net = 4; 28 | bytes ext = 5; 29 | int64 time = 6; 30 | } 31 | 32 | message findnode { 33 | bytes target = 1; 34 | uint32 count = 2; 35 | int64 time = 3; 36 | } 37 | 38 | message neighbors { 39 | repeated bytes nodes = 1; 40 | bool last = 2; 41 | int64 time = 3; 42 | } 43 | -------------------------------------------------------------------------------- /crypto/hast_test.go: -------------------------------------------------------------------------------- 1 | package crypto 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "encoding/hex" 7 | "fmt" 8 | "testing" 9 | ) 10 | 11 | func TestHash(t *testing.T) { 12 | data := "12343" 13 | hash0 := Hash(20, []byte(data)) 14 | hash1 := Hash(32, []byte(data)) 15 | println(hex.EncodeToString(hash0)) 16 | println(hex.EncodeToString(hash1)) 17 | 18 | a := []byte{1, 2} 19 | b := []byte{3, 4} 20 | fmt.Println(hex.EncodeToString(Hash256(a, b))) 21 | fmt.Println(hex.EncodeToString(Hash256([]byte{1, 2, 3, 4}))) 22 | 23 | if !bytes.Equal(Hash256(a, b), Hash256([]byte{1, 2, 3, 4})) { 24 | t.Fatal("not equal") 25 | } 26 | } 27 | 28 | func BenchmarkHash256(b *testing.B) { 29 | buf := make([]byte, 4096) 30 | _, _ = rand.Read(buf) 31 | b.ResetTimer() 32 | for i := 0; i < b.N; i++ { 33 | Hash256(buf) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ledger/verifier/common.go: -------------------------------------------------------------------------------- 1 | package verifier 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ) 6 | 7 | // PENDING represents the block which can't be determined because its dependent transactions were not verified, 8 | // FAIL represents the block which is found illegal or unqualified, 9 | // SUCCESS represents the block is successfully verified. 10 | const ( 11 | PENDING VerifyResult = iota 12 | FAIL 13 | SUCCESS 14 | ) 15 | 16 | // SnapshotPendingTask defines to carry the information of those snapshot block to be processed(PENDING). 17 | type SnapshotPendingTask struct { 18 | Hash *types.Hash 19 | } 20 | 21 | // AccountPendingTask defines to carry the information of those account block to be processed(PENDING). 22 | type AccountPendingTask struct { 23 | Addr *types.Address 24 | Hash *types.Hash 25 | } 26 | -------------------------------------------------------------------------------- /common/helper/math_integer.go: -------------------------------------------------------------------------------- 1 | package helper 2 | 3 | // SafeMul returns multiplication result and whether overflow occurred. 4 | func SafeMul(x, y uint64) (uint64, bool) { 5 | if x == 0 || y == 0 { 6 | return 0, false 7 | } 8 | return x * y, y > MaxUint64/x 9 | } 10 | 11 | // SafeAdd returns the result and whether overflow occurred. 12 | func SafeAdd(x, y uint64) (uint64, bool) { 13 | return x + y, y > MaxUint64-x 14 | } 15 | 16 | func Min(x, y uint64) uint64 { 17 | if x < y { 18 | return x 19 | } 20 | return y 21 | } 22 | 23 | func Max(x, y uint64) uint64 { 24 | if x > y { 25 | return x 26 | } 27 | return y 28 | } 29 | 30 | func MinInt(x, y int) int { 31 | if x < y { 32 | return x 33 | } 34 | return y 35 | } 36 | 37 | func MinInt64(x, y int64) int64 { 38 | if x < y { 39 | return x 40 | } 41 | return y 42 | } 43 | -------------------------------------------------------------------------------- /vm_db/state.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/crypto" 6 | ) 7 | 8 | func (vdb *vmDb) GetReceiptHash() *types.Hash { 9 | kvList := vdb.unsaved().GetStorage() 10 | if len(kvList) <= 0 { 11 | return &types.Hash{} 12 | } 13 | 14 | size := 0 15 | for _, kv := range kvList { 16 | size += len(kv[0]) + len(kv[1]) 17 | } 18 | 19 | hashSource := make([]byte, 0, size) 20 | for _, kv := range kvList { 21 | hashSource = append(hashSource, kv[0]...) 22 | hashSource = append(hashSource, kv[1]...) 23 | } 24 | 25 | hash, _ := types.BytesToHash(crypto.Hash256(hashSource)) 26 | 27 | return &hash 28 | } 29 | 30 | func (vdb *vmDb) Reset() { 31 | vdb.unsaved().Reset() 32 | } 33 | 34 | func (vdb *vmDb) Finish() { 35 | vdb.unsaved().ReleaseRuntime() 36 | } 37 | -------------------------------------------------------------------------------- /wallet/entropystore/models.go: -------------------------------------------------------------------------------- 1 | package entropystore 2 | 3 | const ( 4 | cryptoStoreVersion = 1 5 | ) 6 | 7 | type entropyJSON struct { 8 | PrimaryAddress string `json:"primaryAddress"` 9 | Crypto cryptoJSON `json:"crypto"` 10 | Version int `json:"seedstoreversion"` 11 | Timestamp int64 `json:"timestamp"` 12 | } 13 | 14 | type cryptoJSON struct { 15 | CipherName string `json:"ciphername"` 16 | CipherText string `json:"ciphertext"` 17 | Nonce string `json:"nonce"` 18 | KDF string `json:"kdf"` 19 | ScryptParams scryptParams `json:"scryptparams"` 20 | } 21 | 22 | type scryptParams struct { 23 | N int `json:"n"` 24 | R int `json:"r"` 25 | P int `json:"p"` 26 | KeyLen int `json:"keylen"` 27 | Salt string `json:"salt"` 28 | } 29 | -------------------------------------------------------------------------------- /common/db/xleveldb/util/crc32.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The LevelDB-Go Authors. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license that can be 4 | // found in the LICENSE file. 5 | 6 | package util 7 | 8 | import ( 9 | "hash/crc32" 10 | ) 11 | 12 | var table = crc32.MakeTable(crc32.Castagnoli) 13 | 14 | // CRC is a CRC-32 checksum computed using Castagnoli's polynomial. 15 | type CRC uint32 16 | 17 | // NewCRC creates a new crc based on the given bytes. 18 | func NewCRC(b []byte) CRC { 19 | return CRC(0).Update(b) 20 | } 21 | 22 | // Update updates the crc with the given bytes. 23 | func (c CRC) Update(b []byte) CRC { 24 | return CRC(crc32.Update(uint32(c), table, b)) 25 | } 26 | 27 | // Value returns a masked crc. 28 | func (c CRC) Value() uint32 { 29 | return uint32(c>>15|c<<17) + 0xa282ead8 30 | } 31 | -------------------------------------------------------------------------------- /ledger/chain/utils/keys.go: -------------------------------------------------------------------------------- 1 | package chain_utils 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | type DBKey interface { 6 | Bytes() []byte 7 | String() string 8 | } 9 | 10 | type DBKeyAddressRefill interface { 11 | AddressRefill(addr types.Address) 12 | } 13 | 14 | type DBKeyHashRefill interface { 15 | HashRefill(hash types.Hash) 16 | } 17 | 18 | type DBKeyHeightRefill interface { 19 | HeightRefill(height uint64) 20 | } 21 | 22 | type DBKeyRealKeyRefill interface { 23 | KeyRefill(real StorageRealKey) 24 | } 25 | 26 | type DBKeyTokenIdRefill interface { 27 | TokenIdRefill(tokenId types.TokenTypeId) 28 | } 29 | 30 | type DBKeyStorage interface { 31 | DBKey 32 | DBKeyAddressRefill 33 | DBKeyRealKeyRefill 34 | } 35 | 36 | type DBKeyBalance interface { 37 | DBKey 38 | DBKeyAddressRefill 39 | DBKeyTokenIdRefill 40 | } 41 | -------------------------------------------------------------------------------- /ledger/chain/meta.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | import ( 4 | "github.com/syndtr/goleveldb/leveldb" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | const ( 10 | GenesisKey = byte(0) 11 | ) 12 | 13 | func (c *chain) WriteGenesisCheckSum(hash types.Hash) error { 14 | if err := c.metaDB.Put([]byte{GenesisKey}, hash.Bytes(), nil); err != nil { 15 | return err 16 | } 17 | return nil 18 | } 19 | 20 | func (c *chain) QueryGenesisCheckSum() (*types.Hash, error) { 21 | value, err := c.metaDB.Get([]byte{GenesisKey}, nil) 22 | if err != nil { 23 | if err == leveldb.ErrNotFound { 24 | return nil, nil 25 | } 26 | return nil, err 27 | } 28 | if len(value) <= 0 { 29 | return nil, nil 30 | } 31 | 32 | checkSum, err := types.BytesToHash(value) 33 | if err != nil { 34 | return nil, err 35 | } 36 | return &checkSum, nil 37 | } 38 | -------------------------------------------------------------------------------- /ledger/consensus/core/consensus.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | type VoteType uint8 10 | 11 | const ( 12 | NORMAL = VoteType(0) 13 | SUCCESS_RATE_PROMOTION = VoteType(1) 14 | SUCCESS_RATE_DEMOTION = VoteType(2) 15 | RANDOM_PROMOTION = VoteType(3) 16 | ) 17 | 18 | type Vote struct { 19 | Name string 20 | Addr types.Address 21 | Balance *big.Int 22 | Type []VoteType 23 | } 24 | 25 | type ByBalance []*Vote 26 | 27 | func (a ByBalance) Len() int { return len(a) } 28 | func (a ByBalance) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 29 | func (a ByBalance) Less(i, j int) bool { 30 | 31 | r := a[j].Balance.Cmp(a[i].Balance) 32 | if r == 0 { 33 | return a[i].Name < a[j].Name 34 | } else { 35 | return r < 0 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /common/db/xleveldb/filter.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, Suryandaru Triandana 2 | // All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license that can be 5 | // found in the LICENSE file. 6 | 7 | package leveldb 8 | 9 | import ( 10 | "github.com/vitelabs/go-vite/v2/common/db/xleveldb/filter" 11 | ) 12 | 13 | type iFilter struct { 14 | filter.Filter 15 | } 16 | 17 | func (f iFilter) Contains(filter, key []byte) bool { 18 | return f.Filter.Contains(filter, internalKey(key).ukey()) 19 | } 20 | 21 | func (f iFilter) NewGenerator() filter.FilterGenerator { 22 | return iFilterGenerator{f.Filter.NewGenerator()} 23 | } 24 | 25 | type iFilterGenerator struct { 26 | filter.FilterGenerator 27 | } 28 | 29 | func (g iFilterGenerator) Add(key []byte) { 30 | g.FilterGenerator.Add(internalKey(key).ukey()) 31 | } 32 | -------------------------------------------------------------------------------- /cmd/utils/flock/flock.go: -------------------------------------------------------------------------------- 1 | package flock 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | // Releaser provides the Release method to release chain file lock. 9 | type Releaser interface { 10 | Release() error 11 | } 12 | 13 | // New locks the file with the provided name. If the file does not exist, it is 14 | // created. The returned Releaser is used to release the lock. existed is true 15 | // if the file to lock already existed. A non-nil error is returned if the 16 | // locking has failed. Neither this function nor the returned Releaser is 17 | // goroutine-safe. 18 | func New(fileName string) (r Releaser, existed bool, err error) { 19 | if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil { 20 | return 21 | } 22 | 23 | _, err = os.Stat(fileName) 24 | existed = err == nil 25 | 26 | r, err = newLock(fileName) 27 | return 28 | } 29 | -------------------------------------------------------------------------------- /common/config/genesis_test.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | 8 | "github.com/vitelabs/go-vite/v2/common/types" 9 | "github.com/vitelabs/go-vite/v2/crypto" 10 | ) 11 | 12 | func TestMakeGenesisAccountConfig(t *testing.T) { 13 | cfg := MainnetGenesis() 14 | if !IsCompleteGenesisConfig(cfg) { 15 | t.Fatalf("convert genesis config failed") 16 | } 17 | } 18 | 19 | func TestGenesisCfg(t *testing.T) { 20 | hash, err := types.BytesToHash(crypto.Hash256([]byte(GenesisJson()))) 21 | if err != nil { 22 | t.Fatal(err) 23 | } 24 | t.Log(hash) 25 | assert.Equal(t, "4c56bfcc9a28d902352c3d17fcd9de147538ae9f7f71aff975433b8d403e45df", hash.String()) 26 | } 27 | 28 | func TestLoadGenesisCfg(t *testing.T) { 29 | loadFromGenesisFile("~/go/src/github.com/vitelabs/go-vite/conf/evm/genesis.json") 30 | } 31 | -------------------------------------------------------------------------------- /ledger/chain/sync_cache/reader_test.go: -------------------------------------------------------------------------------- 1 | package sync_cache 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | func TestRead3(t *testing.T) { 9 | t.Skip("Skipped by default. This test can be used to inspect sync cache.") 10 | 11 | filename := "xxxxx/f_57990301_57991300_1617778532" 12 | file, err := os.OpenFile(filename, os.O_RDWR, 0666) 13 | if err != nil { 14 | t.Fatal(err) 15 | } 16 | reader := &Reader{ 17 | cache: nil, 18 | file: file, 19 | readBuffer: make([]byte, 8*1024), 20 | item: nil, 21 | } 22 | for { 23 | 24 | ab, sb, err := reader.Read() 25 | if err != nil { 26 | break 27 | } else if ab != nil { 28 | t.Logf("[ab] height:%d, hash:%s, address:%s\n", ab.Height, ab.Hash, ab.AccountAddress) 29 | } else if sb != nil { 30 | t.Logf("[sb] height:%d, hash:%s\n", sb.Height, sb.Hash) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /client/rpc/dex_trade.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/rpc" 6 | "github.com/vitelabs/go-vite/v2/rpcapi/api/dex" 7 | ) 8 | 9 | // ContractApi ... 10 | type DexTradeApi interface { 11 | GetOrdersFromMarket(tradeToken, quoteToken types.TokenTypeId, side bool, begin, end int) (ordersRes *dex.OrdersRes, err error) 12 | } 13 | 14 | type dexTradeApi struct { 15 | cc *rpc.Client 16 | } 17 | 18 | func NewDexTradeApi(cc *rpc.Client) DexTradeApi { 19 | return &dexTradeApi{cc: cc} 20 | } 21 | 22 | func (ci dexTradeApi) GetOrdersFromMarket(tradeToken, quoteToken types.TokenTypeId, side bool, begin, end int) (result *dex.OrdersRes, err error) { 23 | result = &dex.OrdersRes{} 24 | err = ci.cc.Call(&result, "dextrade_getOrdersFromMarket", tradeToken, quoteToken, side, begin, end) 25 | return 26 | } 27 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.15-alpine as maker 2 | 3 | WORKDIR /go/src/github.com/vitelabs/go-vite 4 | 5 | COPY go.mod . 6 | COPY go.sum . 7 | 8 | RUN GO111MODULE=on go mod download 9 | 10 | ADD . . 11 | 12 | RUN GO111MODULE=on go build -mod=readonly -o gvite cmd/gvite/main.go 13 | 14 | FROM alpine:3.8 15 | 16 | RUN apk update \ 17 | && apk upgrade \ 18 | && apk add --no-cache bash \ 19 | bash-doc \ 20 | bash-completion \ 21 | && rm -rf /var/cache/apk/* \ 22 | && /bin/bash 23 | 24 | RUN apk add --no-cache ca-certificates 25 | 26 | WORKDIR /root 27 | 28 | COPY --from=maker /go/src/github.com/vitelabs/go-vite/gvite . 29 | COPY --from=maker /go/src/github.com/vitelabs/go-vite/conf conf 30 | COPY --from=maker /go/src/github.com/vitelabs/go-vite/conf/node_config.json . 31 | 32 | EXPOSE 8483 8484 48132 41420 8483/udp 33 | ENTRYPOINT ["./gvite"] 34 | -------------------------------------------------------------------------------- /ledger/chain/test_tools/data_dir.go: -------------------------------------------------------------------------------- 1 | package test_tools 2 | 3 | import ( 4 | "os" 5 | "os/user" 6 | "path/filepath" 7 | "runtime" 8 | ) 9 | 10 | func DefaultDataDir() string { 11 | // Try to place the data folder in the user's home dir 12 | home := homeDir() 13 | if home != "" { 14 | if runtime.GOOS == "darwin" { 15 | return filepath.Join(home, "Library", "GVite") 16 | } else if runtime.GOOS == "windows" { 17 | return filepath.Join(home, "AppData", "Roaming", "GVite") 18 | } else { 19 | return filepath.Join(home, ".gvite") 20 | } 21 | } 22 | // As we cannot guess chain stable location, return empty and handle later 23 | return "" 24 | } 25 | 26 | func homeDir() string { 27 | if home := os.Getenv("HOME"); home != "" { 28 | return home 29 | } 30 | if usr, err := user.Current(); err == nil { 31 | return usr.HomeDir 32 | } 33 | return "" 34 | } 35 | -------------------------------------------------------------------------------- /ledger/onroad/access_test.go: -------------------------------------------------------------------------------- 1 | package onroad 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/config" 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | "github.com/vitelabs/go-vite/v2/ledger/test_tools" 9 | ) 10 | 11 | func Test_onroad(t *testing.T) { 12 | c, tempDir := test_tools.NewTestChainInstance(t.Name(), true, config.MockGenesis()) 13 | defer test_tools.ClearChain(c, tempDir) 14 | 15 | pageNum := 0 16 | addr, _ := types.HexToAddress("vite_0000000000000000000000000000000000000003f6af7459b9") 17 | for { 18 | blockList, err := c.GetOnRoadBlocksByAddr(addr, pageNum, 100) 19 | if err != nil { 20 | t.Fatal(err) 21 | } 22 | if len(blockList) <= 0 { 23 | break 24 | } 25 | t.Log(len(blockList)) 26 | for _, block := range blockList { 27 | t.Log("hash", block.Hash, "height", block.Height) 28 | } 29 | pageNum++ 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ledger/pool/batch/level.go: -------------------------------------------------------------------------------- 1 | package batch 2 | 3 | import "github.com/vitelabs/go-vite/v2/common/types" 4 | 5 | type level struct { 6 | index int 7 | closed bool 8 | done bool 9 | } 10 | 11 | func (self *level) Index() int { 12 | return self.index 13 | } 14 | 15 | func (self *level) Close() { 16 | if self.closed { 17 | panic("has closed") 18 | } 19 | self.closed = true 20 | } 21 | 22 | func (self *level) Closed() bool { 23 | return self.closed 24 | } 25 | 26 | func (self *level) Done() { 27 | self.done = true 28 | } 29 | 30 | func (self *level) HasDone() bool { 31 | return self.done 32 | } 33 | 34 | func newLevel(snapshot bool, index int, sHash *types.Hash) Level { 35 | if snapshot { 36 | return newSnapshotLevel(index) 37 | } else { 38 | return newAccountLevel(index, sHash) 39 | } 40 | } 41 | 42 | type ownerLevel struct { 43 | owner *types.Address 44 | level int 45 | } 46 | -------------------------------------------------------------------------------- /ledger/consensus/consensus_verifier.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces" 6 | core "github.com/vitelabs/go-vite/v2/interfaces/core" 7 | ) 8 | 9 | type virtualVerifier struct { 10 | } 11 | 12 | func NewVirtualVerifier() interfaces.ConsensusVerifier { 13 | return &virtualVerifier{} 14 | } 15 | 16 | func (virtualVerifier) VerifyAccountProducer(block *core.AccountBlock) (bool, error) { 17 | return true, nil 18 | } 19 | 20 | func (virtualVerifier) VerifyABsProducer(abs map[types.Gid][]*core.AccountBlock) ([]*core.AccountBlock, error) { 21 | var result []*core.AccountBlock 22 | for _, v := range abs { 23 | result = append(result, v...) 24 | } 25 | return result, nil 26 | } 27 | 28 | func (virtualVerifier) VerifySnapshotProducer(block *core.SnapshotBlock) (bool, error) { 29 | return true, nil 30 | } 31 | -------------------------------------------------------------------------------- /net/sync_server_test.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "math/rand" 5 | net2 "net" 6 | "sync/atomic" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func Test_File_Server(t *testing.T) { 12 | const addr = "localhost:8484" 13 | fs := newSyncServer(addr, nil, nil) 14 | 15 | if err := fs.start(); err != nil { 16 | t.Fatal(err) 17 | } 18 | 19 | var conns int32 20 | for i := 0; i < 100; i++ { 21 | go func() { 22 | conn, err := net2.Dial("tcp", addr) 23 | if err != nil { 24 | t.Fatal(err) 25 | } 26 | 27 | atomic.AddInt32(&conns, 1) 28 | 29 | if rand.Intn(10) > 5 { 30 | time.Sleep(time.Second) 31 | conn.Close() 32 | atomic.AddInt32(&conns, -1) 33 | } 34 | }() 35 | } 36 | 37 | time.Sleep(3 * time.Second) 38 | 39 | if len(fs.sconnMap) != int(conns) { 40 | t.Fail() 41 | } 42 | 43 | fs.stop() 44 | 45 | if len(fs.sconnMap) != 0 { 46 | t.Fail() 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /net/block_feed_test.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 9 | ) 10 | 11 | func TestBlockFeed_Black(t *testing.T) { 12 | const black = "6771bc124fed97302328c13fb9a97919c8963b7b1f79a431091c7ace00ec28f4" 13 | 14 | feed := newBlockFeeder(make(map[types.Hash]struct{})) 15 | 16 | feed.SubscribeSnapshotBlock(func(block *ledger.SnapshotBlock, source types.BlockSource) { 17 | if block.Hash.String() == black { 18 | t.Fail() 19 | } else { 20 | fmt.Printf("%s/%d", block.Hash, block.Height) 21 | } 22 | }) 23 | 24 | hash, _ := types.HexToHash(black) 25 | 26 | feed.notifySnapshotBlock(&ledger.SnapshotBlock{ 27 | Hash: hash, 28 | }, types.RemoteCache) 29 | 30 | feed.notifySnapshotBlock(&ledger.SnapshotBlock{ 31 | Hash: types.Hash{}, 32 | }, types.RemoteCache) 33 | } 34 | -------------------------------------------------------------------------------- /vm_db/vm_log.go: -------------------------------------------------------------------------------- 1 | package vm_db 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 8 | ) 9 | 10 | func (vdb *vmDb) AddLog(log *ledger.VmLog) { 11 | vdb.unsaved().AddLog(log) 12 | } 13 | 14 | func (vdb *vmDb) GetLogList() ledger.VmLogList { 15 | return vdb.unsaved().GetLogList() 16 | } 17 | 18 | func (vdb *vmDb) GetHistoryLogList(logHash *types.Hash) (ledger.VmLogList, error) { 19 | return vdb.chain.GetVmLogList(logHash) 20 | } 21 | 22 | func (vdb *vmDb) GetLogListHash() *types.Hash { 23 | var sbHeight uint64 24 | if !vdb.isGenesis { 25 | latestSb, err := vdb.LatestSnapshotBlock() 26 | if err != nil { 27 | panic(fmt.Sprintf("Error: %s", err.Error())) 28 | } 29 | sbHeight = latestSb.Height 30 | } 31 | 32 | return vdb.unsaved().GetLogListHash(sbHeight, *vdb.Address(), vdb.PrevAccountBlockHash()) 33 | } 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | .DS_Store 9 | gvite 10 | !gvite/ 11 | gvite.log 12 | 13 | # vscode 14 | .vscode 15 | 16 | # Test binary, build with `go test -c` 17 | *.test 18 | testdata/trie 19 | testdata/vm_context 20 | testdata/ledger 21 | testdata/ledger_file 22 | 23 | # Output of the go coverage tool, specifically when used with LiteIDE 24 | *.out 25 | 26 | # Leveldb database files for test, put it here temporarily 27 | vite_leveldb_database 28 | vite.p2p.db 29 | 30 | # idea files 31 | .idea/ 32 | 33 | # Build files 34 | build/ 35 | 36 | vite/net/simular/genesis.go 37 | 38 | **/p2p/**/simular/** 39 | !**/p2p/**/simular/**/*.go 40 | **/net/**/simular/** 41 | !**/net/**/simular/**/*.go 42 | 43 | # node.js 44 | node_modules 45 | *.log 46 | package-lock.json 47 | sw.* 48 | workbox-* 49 | 50 | # bin/dump_branch_diff 51 | commits-logs/ 52 | -------------------------------------------------------------------------------- /conf/evm/node_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "Identity": "foobar", 3 | "NetID": 1, 4 | "GenesisFile": "/root/conf/evm/genesis.json", 5 | "Single": true, 6 | "RPCEnabled": true, 7 | "HttpHost": "0.0.0.0", 8 | "HttpPort": 48132, 9 | "HttpEnabled": true, 10 | "WSEnabled": false, 11 | "HttpVirtualHosts": [], 12 | "IPCEnabled": true, 13 | "IPCPath": "ipc/gvite.ipc", 14 | "PublicModules": [ 15 | "ledger", 16 | "net", 17 | "contract", 18 | "util", 19 | "debug", 20 | "sbpstats", 21 | "wallet" 22 | ], 23 | "Miner": true, 24 | "CoinBase": "0:vite_3167c9421c8a4cb642d613082dfcef932e26063867f277ec0f", 25 | "EntropyStorePath": "/root/conf/evm/vite_3167c9421c8a4cb642d613082dfcef932e26063867f277ec0f", 26 | "EntropyStorePassword": "123456", 27 | "LogLevel": "info", 28 | "OpenPlugins": true, 29 | "SubscribeEnabled": true, 30 | "TxDexEnable": true, 31 | "VmLogAll": true 32 | } 33 | -------------------------------------------------------------------------------- /cmd/utils/flock/flock_solaris.go: -------------------------------------------------------------------------------- 1 | package flock 2 | 3 | import ( 4 | "os" 5 | "syscall" 6 | ) 7 | 8 | type unixLock struct { 9 | f *os.File 10 | } 11 | 12 | func (l *unixLock) Release() error { 13 | if err := l.set(false); err != nil { 14 | return err 15 | } 16 | return l.f.Close() 17 | } 18 | 19 | func (l *unixLock) set(lock bool) error { 20 | flock := syscall.Flock_t{ 21 | Type: syscall.F_UNLCK, 22 | Start: 0, 23 | Len: 0, 24 | Whence: 1, 25 | } 26 | if lock { 27 | flock.Type = syscall.F_WRLCK 28 | } 29 | return syscall.FcntlFlock(l.f.Fd(), syscall.F_SETLK, &flock) 30 | } 31 | 32 | func newLock(fileName string) (Releaser, error) { 33 | f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) 34 | if err != nil { 35 | return nil, err 36 | } 37 | l := &unixLock{f} 38 | err = l.set(true) 39 | if err != nil { 40 | f.Close() 41 | return nil, err 42 | } 43 | return l, nil 44 | } 45 | -------------------------------------------------------------------------------- /ledger/pool/batch/level_snapshot.go: -------------------------------------------------------------------------------- 1 | package batch 2 | 3 | import ( 4 | "github.com/pkg/errors" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | type snapshotLevel struct { 10 | level 11 | bu *bucket 12 | } 13 | 14 | func newSnapshotLevel(index int) *snapshotLevel { 15 | return &snapshotLevel{bu: newBucket(nil), level: level{index: index}} 16 | } 17 | 18 | func (self *snapshotLevel) Add(b Item) error { 19 | if self.Closed() { 20 | panic(errors.New("snapshot level is closed.")) 21 | } 22 | return self.bu.add(b) 23 | } 24 | 25 | func (self *snapshotLevel) SHash() *types.Hash { 26 | return nil 27 | } 28 | 29 | func (self *snapshotLevel) Snapshot() bool { 30 | return true 31 | } 32 | 33 | func (self *snapshotLevel) Buckets() (result []Bucket) { 34 | result = append(result, self.bu) 35 | return 36 | } 37 | 38 | func (self *snapshotLevel) Size() int { 39 | return len(self.bu.Items()) 40 | } 41 | -------------------------------------------------------------------------------- /ledger/consensus/core/time_index.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | type TimeIndex interface { 8 | Index2Time(index uint64) (time.Time, time.Time) 9 | Time2Index(t time.Time) uint64 10 | } 11 | 12 | type timeIndex struct { 13 | GenesisTime time.Time 14 | // second 15 | Interval time.Duration 16 | } 17 | 18 | func (self timeIndex) Index2Time(index uint64) (time.Time, time.Time) { 19 | sTime := self.GenesisTime.Add(self.Interval * time.Duration(index)) 20 | eTime := self.GenesisTime.Add(self.Interval * time.Duration(index+1)) 21 | return sTime, eTime 22 | } 23 | func (self timeIndex) Time2Index(t time.Time) uint64 { 24 | subSec := int64(t.Sub(self.GenesisTime).Seconds()) 25 | i := uint64(subSec) / uint64(self.Interval.Seconds()) 26 | return i 27 | } 28 | 29 | func NewTimeIndex(t time.Time, interval time.Duration) TimeIndex { 30 | return &timeIndex{GenesisTime: t, Interval: interval} 31 | } 32 | -------------------------------------------------------------------------------- /common/db/xleveldb/util/range.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014, Suryandaru Triandana 2 | // All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license that can be 5 | // found in the LICENSE file. 6 | 7 | package util 8 | 9 | // Range is a key range. 10 | type Range struct { 11 | // Start of the key range, include in the range. 12 | Start []byte 13 | 14 | // Limit of the key range, not include in the range. 15 | Limit []byte 16 | } 17 | 18 | // BytesPrefix returns key range that satisfy the given prefix. 19 | // This only applicable for the standard 'bytes comparer'. 20 | func BytesPrefix(prefix []byte) *Range { 21 | var limit []byte 22 | for i := len(prefix) - 1; i >= 0; i-- { 23 | c := prefix[i] 24 | if c < 0xff { 25 | limit = make([]byte, i+1) 26 | copy(limit, prefix) 27 | limit[i] = c + 1 28 | break 29 | } 30 | } 31 | return &Range{prefix, limit} 32 | } 33 | -------------------------------------------------------------------------------- /common/lock_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | _ "net/http/pprof" 8 | "sync" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func TestRwLock(t *testing.T) { 14 | //远程获取pprof数据 15 | go func() { 16 | log.Println(http.ListenAndServe("localhost:8070", nil)) 17 | }() 18 | 19 | mutex := sync.RWMutex{} 20 | 21 | //ch1 := make(chan int) 22 | ch2 := make(chan int) 23 | ch3 := make(chan int) 24 | //ch4 := make(chan int) 25 | 26 | wg := sync.WaitGroup{} 27 | 28 | wg.Add(2) 29 | go func() { 30 | <-ch3 31 | mutex.RLock() 32 | ch2 <- 1 33 | 34 | time.Sleep(30 * time.Millisecond) 35 | mutex.RLock() 36 | defer mutex.RUnlock() 37 | defer mutex.RUnlock() 38 | 39 | wg.Done() 40 | }() 41 | 42 | go func() { 43 | <-ch2 44 | mutex.Lock() 45 | 46 | defer mutex.Unlock() 47 | wg.Done() 48 | }() 49 | 50 | ch3 <- 1 51 | wg.Wait() 52 | fmt.Println("-------") 53 | } 54 | -------------------------------------------------------------------------------- /ledger/chain/plugins/onroad_info_test.go: -------------------------------------------------------------------------------- 1 | package chain_plugins 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ) 6 | 7 | var ( 8 | contract1, _ = types.BytesToAddress([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}) 9 | contract2, _ = types.BytesToAddress([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}) 10 | contract3, _ = types.BytesToAddress([]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}) 11 | caller1, _ = types.BytesToAddress([]byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}) 12 | caller2, _ = types.BytesToAddress([]byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}) 13 | caller3, _ = types.BytesToAddress([]byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}) 14 | 15 | ContractList = []*types.Address{&contract1, &contract2, &contract3} 16 | GeneralList = []*types.Address{&caller1, &caller2, &caller3} 17 | ) 18 | -------------------------------------------------------------------------------- /ledger/consensus/dpos.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | "github.com/vitelabs/go-vite/v2/ledger/consensus/core" 8 | "github.com/vitelabs/go-vite/v2/log15" 9 | ) 10 | 11 | type dposReader struct { 12 | snapshot DposReader 13 | contracts *contractsCs 14 | 15 | log log15.Logger 16 | } 17 | 18 | func (self *dposReader) getDposConsensus(gid types.Gid) (DposReader, error) { 19 | if gid == types.SNAPSHOT_GID { 20 | return self.snapshot, nil 21 | } 22 | 23 | return self.contracts.getOrLoadGid(gid) 24 | } 25 | 26 | type DposReader interface { 27 | ElectionIndex(index uint64) (*electionResult, error) 28 | GetInfo() *core.GroupInfo 29 | Time2Index(t time.Time) uint64 30 | Index2Time(i uint64) (time.Time, time.Time) 31 | GenProofTime(t uint64) time.Time 32 | VerifyProducer(address types.Address, t time.Time) (bool, error) 33 | } 34 | 35 | type DposVerifier interface { 36 | } 37 | -------------------------------------------------------------------------------- /interfaces/core/hash_height_test.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | ) 9 | 10 | func ExampleHashHeight() { 11 | var points = make([][2]*HashHeight, 2) 12 | 13 | points[0] = [2]*HashHeight{ 14 | {100, types.Hash{}}, 15 | {200, types.Hash{}}, 16 | } 17 | 18 | points[1] = [2]*HashHeight{ 19 | {201, types.Hash{}}, 20 | {300, types.Hash{}}, 21 | } 22 | 23 | data, err := json.Marshal(points) 24 | if err != nil { 25 | panic(err) 26 | } 27 | 28 | fmt.Printf("%s\n", data) 29 | // Output: 30 | // [[{"height":100,"hash":"0000000000000000000000000000000000000000000000000000000000000000"},{"height":200,"hash":"0000000000000000000000000000000000000000000000000000000000000000"}],[{"height":201,"hash":"0000000000000000000000000000000000000000000000000000000000000000"},{"height":300,"hash":"0000000000000000000000000000000000000000000000000000000000000000"}]] 31 | } 32 | -------------------------------------------------------------------------------- /vm/abi/numbers.go: -------------------------------------------------------------------------------- 1 | package abi 2 | 3 | import ( 4 | "math/big" 5 | "reflect" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/helper" 8 | "github.com/vitelabs/go-vite/v2/common/types" 9 | ) 10 | 11 | var ( 12 | bigT = reflect.TypeOf(&big.Int{}) 13 | derefbigT = reflect.TypeOf(big.Int{}) 14 | uint8T = reflect.TypeOf(uint8(0)) 15 | uint16T = reflect.TypeOf(uint16(0)) 16 | uint32T = reflect.TypeOf(uint32(0)) 17 | uint64T = reflect.TypeOf(uint64(0)) 18 | int8T = reflect.TypeOf(int8(0)) 19 | int16T = reflect.TypeOf(int16(0)) 20 | int32T = reflect.TypeOf(int32(0)) 21 | int64T = reflect.TypeOf(int64(0)) 22 | addressT = reflect.TypeOf(types.Address{}) 23 | gidT = reflect.TypeOf(types.Gid{}) 24 | tokenIdT = reflect.TypeOf(types.TokenTypeId{}) 25 | ) 26 | 27 | // U256 converts a big Int into a 256bit VM number. 28 | func U256(n *big.Int) []byte { 29 | return helper.PaddedBigBytes(helper.U256(n), helper.WordSize) 30 | } 31 | -------------------------------------------------------------------------------- /cmd/updater_consensus/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "fmt" 7 | 8 | "github.com/syndtr/goleveldb/leveldb" 9 | 10 | "github.com/vitelabs/go-vite/v2/ledger/consensus/cdb" 11 | ) 12 | 13 | var index = flag.Uint64("index", 0, "index") 14 | var dir = flag.String("dataDir", "", "consensus data dir") 15 | 16 | func main() { 17 | flag.Parse() 18 | if *index == 0 { 19 | panic("error index") 20 | } 21 | if *dir == "" { 22 | panic("err dir") 23 | } 24 | d, err := leveldb.OpenFile(*dir, nil) 25 | if err != nil { 26 | panic(err) 27 | } 28 | 29 | db := cdb.NewConsensusDB(d) 30 | point, err := db.GetPointByHeight(cdb.IndexPointDay, *index) 31 | if err != nil { 32 | panic(err) 33 | } 34 | bytes, err := json.Marshal(point) 35 | if err != nil { 36 | panic(err) 37 | } 38 | fmt.Println(string(bytes)) 39 | err = db.DeletePointByHeight(cdb.IndexPointDay, *index) 40 | if err != nil { 41 | panic(err) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /conf/evm/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ``` 4 | # run local node 5 | docker run -v ~/.gvite/ipc:/root/ipc -p 127.0.0.1:48132:48132 --rm vitelabs/gvite-nightly:latest --config conf/evm/node_config.json 6 | 7 | # query local node height 8 | docker run -v ~/.gvite/ipc:/root/ipc --rm vitelabs/gvite-nightly:latest rpc /root/ipc/gvite.ipc ledger_getSnapshotChainHeight 9 | 10 | # mine a snapshot block 11 | docker run -v ~/.gvite/ipc:/root/ipc --rm vitelabs/gvite-nightly:latest rpc /root/ipc/gvite.ipc miner_mine 12 | 13 | 14 | # query local node height 15 | curl --location --request POST 'http://127.0.0.1:48132' --header 'Content-Type: application/json' --data-raw '{ "jsonrpc": "2.0", "id": 1, "method":"ledger_getSnapshotChainHeight", "params":null}' 16 | 17 | 18 | # mine a snapshot block 19 | curl --location --request POST 'http://127.0.0.1:48132' --header 'Content-Type: application/json' --data-raw '{ "jsonrpc": "2.0", "id": 1, "method":"miner_mine", "params":null}' 20 | 21 | ``` -------------------------------------------------------------------------------- /ledger/onroad/worker.go: -------------------------------------------------------------------------------- 1 | package onroad 2 | 3 | const ( 4 | create = iota 5 | start 6 | stop 7 | ) 8 | 9 | // Worker lists the methods that the "Worker" need to be implemented. 10 | type Worker interface { 11 | Status() int 12 | Start() 13 | Stop() 14 | Close() error 15 | } 16 | 17 | var ( 18 | // POMAXPROCS is used to limit the use of number of operating system threads. 19 | POMAXPROCS = 2 20 | // ContractTaskProcessorSize is used to limit the number of processors. 21 | ContractTaskProcessorSize = POMAXPROCS 22 | ) 23 | 24 | type inferiorState int 25 | 26 | const ( 27 | // RETRY represents a state which the processor can retry to handle the onroad from a particular caller 28 | // to a particular contract in the next second during a block period. 29 | RETRY inferiorState = iota 30 | // OUT represents a state which the processor won't handle the onroad from a particular caller 31 | // to a particular contract during a block period any more. 32 | OUT 33 | ) 34 | -------------------------------------------------------------------------------- /common/vitepb/account_block.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package vitepb; 4 | 5 | message AccountBlock { 6 | enum BlockType { 7 | Unknown = 0; 8 | SendCreate = 1; 9 | SendCall = 2; 10 | SendReward = 3; 11 | Receive = 4; 12 | ReceiveError = 5; 13 | SendRefund = 6; 14 | 15 | GenesisReceive = 7; 16 | } 17 | 18 | BlockType blockType = 1; 19 | bytes hash = 2; 20 | uint64 height = 3; 21 | bytes prevHash = 4; 22 | 23 | bytes accountAddress = 5; 24 | 25 | bytes publicKey = 6; 26 | 27 | bytes toAddress = 7; 28 | 29 | bytes amount = 8; 30 | 31 | bytes tokenId = 9; 32 | 33 | bytes fromBlockHash = 10; 34 | 35 | bytes data = 11; 36 | 37 | uint64 quota = 12; 38 | 39 | bytes fee = 13; 40 | 41 | bytes StateHash = 14; 42 | 43 | bytes logHash = 15; 44 | 45 | bytes difficulty = 16; 46 | 47 | bytes nonce = 17; 48 | 49 | repeated AccountBlock SendBlockList = 18; 50 | 51 | bytes signature = 19; 52 | 53 | uint64 quotaUsed = 20; 54 | } -------------------------------------------------------------------------------- /cmd/nodemanager/subcmd_node_manager.go: -------------------------------------------------------------------------------- 1 | package nodemanager 2 | 3 | import ( 4 | "gopkg.in/urfave/cli.v1" 5 | 6 | "github.com/vitelabs/go-vite/v2/node" 7 | ) 8 | 9 | type SubCmdNodeManager struct { 10 | ctx *cli.Context 11 | node *node.Node 12 | } 13 | 14 | func NewSubCmdNodeManager(ctx *cli.Context, maker NodeMaker) (*SubCmdNodeManager, error) { 15 | 16 | node, err := maker.MakeNode(ctx) 17 | if err != nil { 18 | return nil, err 19 | } 20 | return &SubCmdNodeManager{ 21 | ctx: ctx, 22 | node: node, 23 | }, nil 24 | } 25 | 26 | func (nodeManager *SubCmdNodeManager) Start() error { 27 | 28 | // Start up the node 29 | err := StartNode(nodeManager.node) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | return nil 35 | } 36 | 37 | func (nodeManager *SubCmdNodeManager) Stop() error { 38 | 39 | StopNode(nodeManager.node) 40 | 41 | return nil 42 | } 43 | 44 | func (nodeManager *SubCmdNodeManager) Node() *node.Node { 45 | 46 | return nodeManager.node 47 | } 48 | -------------------------------------------------------------------------------- /contracts-vite/contracts/ViteToken.sol: -------------------------------------------------------------------------------- 1 | // contracts/ViteToken.sol 2 | // SPDX-License-Identifier: GPL-3.03 3 | pragma solidity ^0.6.0; 4 | 5 | // @openzeppelin/contracts@v3.3.0 6 | import "@openzeppelin/contracts/math/SafeMath.sol"; 7 | import "@openzeppelin/contracts/access/Ownable.sol"; 8 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 9 | import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; 10 | 11 | contract ViteToken is ERC20PresetMinterPauser { 12 | uint256 private erc20_decimals = 18; 13 | uint256 private erc20_units = 10**erc20_decimals; 14 | 15 | constructor() public ERC20PresetMinterPauser("Vite Token", "VITE") {} 16 | 17 | /** 18 | * @dev See {ERC20-_beforeTokenTransfer}. 19 | */ 20 | function _beforeTokenTransfer( 21 | address from, 22 | address to, 23 | uint256 amount 24 | ) internal override(ERC20PresetMinterPauser) { 25 | super._beforeTokenTransfer(from, to, amount); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ledger/onroad/pool/pool.go: -------------------------------------------------------------------------------- 1 | package onroad_pool 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces" 6 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 7 | ) 8 | 9 | type OnRoadPool interface { 10 | InsertAccountBlocks(orAddr types.Address, blocks []*ledger.AccountBlock) error 11 | DeleteAccountBlocks(orAddr types.Address, blocks []*ledger.AccountBlock) error 12 | 13 | GetOnRoadTotalNumByAddr(addr types.Address) (uint64, error) 14 | GetFrontOnRoadBlocksByAddr(addr types.Address) ([]*ledger.AccountBlock, error) 15 | 16 | IsFrontOnRoadOfCaller(orAddr, caller types.Address, hash types.Hash) (bool, error) 17 | Info() map[string]interface{} 18 | } 19 | 20 | type chainReader interface { 21 | LoadOnRoadRange(gid types.Gid, fn interfaces.LoadOnroadFn) error 22 | GetAccountBlockByHash(blockHash types.Hash) (*ledger.AccountBlock, error) 23 | GetCompleteBlockByHash(blockHash types.Hash) (*ledger.AccountBlock, error) 24 | } 25 | -------------------------------------------------------------------------------- /ledger/onroad/task_pqueue.go: -------------------------------------------------------------------------------- 1 | package onroad 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ) 6 | 7 | type contractTask struct { 8 | Addr types.Address 9 | Index int 10 | Quota uint64 11 | } 12 | 13 | type contractTaskPQueue []*contractTask 14 | 15 | func (q *contractTaskPQueue) Push(x interface{}) { 16 | item := x.(*contractTask) 17 | item.Index = len(*q) 18 | *q = append(*q, item) 19 | } 20 | 21 | func (q *contractTaskPQueue) Pop() interface{} { 22 | old := *q 23 | n := len(old) 24 | item := old[n-1] 25 | item.Index = -1 // for safety 26 | *q = old[0 : n-1] 27 | return item 28 | } 29 | 30 | func (q *contractTaskPQueue) Len() int { return len(*q) } 31 | 32 | func (q *contractTaskPQueue) Less(i, j int) bool { 33 | if (*q)[i].Quota < (*q)[j].Quota { 34 | return false 35 | } 36 | return true 37 | } 38 | 39 | func (q *contractTaskPQueue) Swap(i, j int) { 40 | (*q)[i], (*q)[j] = (*q)[j], (*q)[i] 41 | (*q)[i].Index = i 42 | (*q)[j].Index = j 43 | } 44 | -------------------------------------------------------------------------------- /ledger/pool/batch/bucket.go: -------------------------------------------------------------------------------- 1 | package batch 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | type bucket struct { 10 | bs []Item 11 | last int 12 | owner *types.Address 13 | } 14 | 15 | func (self *bucket) Owner() *types.Address { 16 | return self.owner 17 | } 18 | 19 | func (self *bucket) Items() []Item { 20 | return self.bs 21 | } 22 | 23 | func (self *bucket) add(b Item) error { 24 | if self.last == -1 && len(self.bs) != 0 { 25 | return errors.New("bucket must be empty") 26 | } 27 | 28 | if self.last != -1 { 29 | lastB := self.bs[self.last] 30 | if lastB == nil { 31 | return errors.New("lastB must be exists") 32 | } 33 | if lastB.Hash() != b.PrevHash() { 34 | return errors.New("prev and hash") 35 | } 36 | } 37 | 38 | self.bs = append(self.bs, b) 39 | self.last = self.last + 1 40 | return nil 41 | } 42 | 43 | func newBucket(owner *types.Address) *bucket { 44 | return &bucket{last: -1, owner: owner} 45 | } 46 | -------------------------------------------------------------------------------- /rpcapi/api/dex/util.go: -------------------------------------------------------------------------------- 1 | package dex 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/vitelabs/go-vite/v2" 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | "github.com/vitelabs/go-vite/v2/interfaces" 9 | "github.com/vitelabs/go-vite/v2/vm/contracts/dex" 10 | "github.com/vitelabs/go-vite/v2/vm/util" 11 | ) 12 | 13 | func GetConsensusReader(vite *vite.Vite) *util.VMConsensusReader { 14 | return util.NewVMConsensusReader(vite.Consensus().SBPReader()) 15 | } 16 | 17 | func AmountBytesToString(amt []byte) string { 18 | return new(big.Int).SetBytes(amt).String() 19 | } 20 | 21 | func TokenBytesToString(token []byte) string { 22 | tk, _ := types.BytesToTokenTypeId(token) 23 | return tk.String() 24 | } 25 | 26 | func InnerGetOrderById(db interfaces.VmDb, orderId []byte) (*RpcOrder, error) { 27 | matcher := dex.NewRawMatcher(db) 28 | if order, err := matcher.GetOrderById(orderId); err != nil { 29 | return nil, err 30 | } else { 31 | return OrderToRpc(order), nil 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.github/workflows/dispatch-nightly-build.yml: -------------------------------------------------------------------------------- 1 | name: dispatch-nightly-build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Read buildversion 15 | id: buildversion 16 | uses: juliangruber/read-file-action@v1 17 | with: 18 | path: ./version/buildversion 19 | 20 | - name: Echo buildversion 21 | # trim buildversion and set environment variable 22 | run: echo "${{ steps.buildversion.outputs.content }}" | xargs | echo "buildversion=$(> $GITHUB_ENV 23 | 24 | - name: Repository Dispatch 25 | uses: peter-evans/repository-dispatch@v2 26 | with: 27 | token: ${{ secrets.WORKFLOW_PUBLIC_REPO_PAT }} 28 | repository: vitelabs/go-vite-nightly 29 | event-type: nightly-build-event 30 | client-payload: '{"branch": "master", "tag": "${{ env.buildversion }}"}' -------------------------------------------------------------------------------- /ledger/onroad/manager_test.go: -------------------------------------------------------------------------------- 1 | package onroad 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/config" 8 | "github.com/vitelabs/go-vite/v2/common/types" 9 | "github.com/vitelabs/go-vite/v2/ledger/test_tools" 10 | ) 11 | 12 | func generateUnlockAddress() types.Address { 13 | return types.Address{} 14 | } 15 | 16 | func TestManager_ContractWorker(t *testing.T) { 17 | c, tempDir := test_tools.NewTestChainInstance(t.Name(), true, config.MockGenesis()) 18 | defer test_tools.ClearChain(c, tempDir) 19 | 20 | v := NewMockVite(c) 21 | 22 | addr := generateUnlockAddress() 23 | v.Producer().(*mockProducer).Addr = addr 24 | 25 | manager := NewManager(v.Net(), v.Pool(), v.Producer(), nil, nil) 26 | manager.Init(v.chain) 27 | manager.Start() 28 | 29 | time.AfterFunc(1*time.Second, func() { 30 | t.Log("test c produceEvent ") 31 | v.Producer().(*mockProducer).produceEvent(1 * time.Second) 32 | }) 33 | 34 | time.Sleep(3 * time.Second) 35 | manager.Stop() 36 | } 37 | -------------------------------------------------------------------------------- /vite_mock.go: -------------------------------------------------------------------------------- 1 | package vite 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/config" 5 | nodeconfig "github.com/vitelabs/go-vite/v2/node/config" 6 | "github.com/vitelabs/go-vite/v2/wallet" 7 | ) 8 | 9 | func NewMock(cfg *config.Config, walletManager *wallet.Manager) (vite *Vite, err error) { 10 | var nodeConfig *nodeconfig.Config 11 | if cfg == nil || walletManager == nil { 12 | nodeConfig = &nodeconfig.Config{} 13 | //nodeConfig.ParseFromFile("~/go/src/github.com/vitelabs/go-vite/conf/evm/node_config.json") 14 | } 15 | if cfg == nil { 16 | cfg = nodeConfig.MakeViteConfig() 17 | } 18 | if walletManager == nil { 19 | walletManager = wallet.New(nodeConfig.MakeWalletConfig()) 20 | } 21 | 22 | // TODO: use mocks for net, chain, pool, etc. 23 | 24 | vite = &Vite{ 25 | config: cfg, 26 | walletManager: walletManager, 27 | net: nil, 28 | chain: nil, 29 | pool: nil, 30 | consensus: nil, 31 | verifier: nil, 32 | } 33 | return 34 | } 35 | -------------------------------------------------------------------------------- /ledger/pool/face.go: -------------------------------------------------------------------------------- 1 | package pool 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | type accBlocksSort []*core.AccountBlock 9 | 10 | func (a accBlocksSort) Len() int { 11 | return len(a) 12 | } 13 | func (a accBlocksSort) Ids(i int) []string { 14 | var ids []string 15 | 16 | ids = append(ids, a[i].Hash.Hex()) 17 | if blocks := a[i].SendBlockList; len(blocks) > 0 { 18 | for _, block := range blocks { 19 | ids = append(ids, block.Hash.Hex()) 20 | } 21 | } 22 | return ids 23 | } 24 | 25 | func (a accBlocksSort) Swap(i, j int) { 26 | a[i], a[j] = a[j], a[i] 27 | } 28 | 29 | func (a accBlocksSort) Inputs(i int) []string { 30 | var inputs []string 31 | block := a[i] 32 | if block.Height > types.GenesisHeight { 33 | inputs = append(inputs, a[i].PrevHash.Hex()) 34 | } 35 | if block.IsReceiveBlock() && !block.IsGenesisBlock() { 36 | inputs = append(inputs, block.FromBlockHash.Hex()) 37 | } 38 | return inputs 39 | } 40 | -------------------------------------------------------------------------------- /ledger/chain/utils/conversion.go: -------------------------------------------------------------------------------- 1 | package chain_utils 2 | 3 | import ( 4 | "encoding/binary" 5 | 6 | "github.com/vitelabs/go-vite/v2/ledger/chain/file_manager" 7 | ) 8 | 9 | func SerializeLocation(location *chain_file_manager.Location) []byte { 10 | bytes := make([]byte, 12) 11 | binary.BigEndian.PutUint64(bytes, location.FileId) 12 | 13 | binary.BigEndian.PutUint32(bytes[8:], uint32(location.Offset)) 14 | 15 | return bytes 16 | } 17 | 18 | func DeserializeLocation(bytes []byte) *chain_file_manager.Location { 19 | return chain_file_manager.NewLocation(BytesToUint64(bytes[:8]), int64(binary.BigEndian.Uint32(bytes[8:]))) 20 | } 21 | 22 | func Uint64ToBytes(height uint64) []byte { 23 | bytes := make([]byte, 8) 24 | binary.BigEndian.PutUint64(bytes, height) 25 | return bytes 26 | } 27 | 28 | func Uint64Put(bytes []byte, height uint64) []byte { 29 | binary.BigEndian.PutUint64(bytes, height) 30 | return bytes 31 | } 32 | 33 | func BytesToUint64(bytes []byte) uint64 { 34 | return binary.BigEndian.Uint64(bytes) 35 | } 36 | -------------------------------------------------------------------------------- /common/upgrade/height_point.go: -------------------------------------------------------------------------------- 1 | package upgrade 2 | 3 | type HeightPoint interface { 4 | IsVersion12Upgrade() bool 5 | IsDexFeeUpgrade() bool 6 | } 7 | 8 | type heightPoint struct { 9 | height uint64 10 | } 11 | 12 | func NewHeightPoint(height uint64) HeightPoint { 13 | return &heightPoint{height} 14 | } 15 | 16 | func (p heightPoint) IsDexFeeUpgrade() bool { 17 | return IsDexFeeUpgrade(p.height) 18 | } 19 | 20 | func (p heightPoint) IsVersion12Upgrade() bool { 21 | return IsVersion12Upgrade(p.height) 22 | } 23 | 24 | type mockHeightPoint struct { 25 | box UpgradeBox 26 | height uint64 27 | } 28 | 29 | // IsDexFeeUpgrade implements HeightPoint 30 | func (m mockHeightPoint) IsDexFeeUpgrade() bool { 31 | return m.box.isActive(3, m.height) 32 | } 33 | 34 | // IsVersion12Upgrade implements HeightPoint 35 | func (m mockHeightPoint) IsVersion12Upgrade() bool { 36 | return m.box.isActive(12, m.height) 37 | } 38 | 39 | func NewMockPoint(height uint64, box UpgradeBox) HeightPoint { 40 | return &mockHeightPoint{box, height} 41 | } 42 | -------------------------------------------------------------------------------- /common/fileutils/common_use.go: -------------------------------------------------------------------------------- 1 | package fileutils 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | ) 8 | 9 | func OpenOrCreateFd(dirName string) (*os.File, error) { 10 | var dirFd *os.File 11 | for dirFd == nil { 12 | var openErr error 13 | dirFd, openErr = os.Open(dirName) 14 | if openErr != nil { 15 | if os.IsNotExist(openErr) { 16 | var cErr error 17 | cErr = os.MkdirAll(dirName, 0744) 18 | 19 | if cErr != nil { 20 | return nil, fmt.Errorf("Create %s failed, error is %s", dirName, cErr.Error()) 21 | } 22 | } else { 23 | return nil, fmt.Errorf("os.Open %s failed, error is %s", dirName, openErr.Error()) 24 | } 25 | } 26 | } 27 | 28 | return dirFd, nil 29 | } 30 | 31 | func FileSize(fd *os.File) (int64, error) { 32 | fileInfo, err := fd.Stat() 33 | if err != nil { 34 | return 0, fmt.Errorf("fd.Stat() failed, error is %s", err.Error()) 35 | } 36 | 37 | return fileInfo.Size(), nil 38 | } 39 | 40 | func CreateTempDir() string { 41 | tmpDir, _ := ioutil.TempDir("", "") 42 | return tmpDir 43 | } -------------------------------------------------------------------------------- /ledger/chain/file_manager/location.go: -------------------------------------------------------------------------------- 1 | package chain_file_manager 2 | 3 | import "strconv" 4 | 5 | const ( 6 | LocationSize = 12 7 | ) 8 | 9 | type Location struct { 10 | FileId uint64 11 | Offset int64 12 | } 13 | 14 | func NewLocation(fileId uint64, offset int64) *Location { 15 | return &Location{ 16 | FileId: fileId, 17 | Offset: offset, 18 | } 19 | } 20 | 21 | func (location *Location) Compare(a *Location) int { 22 | if location.FileId < a.FileId { 23 | return -1 24 | } 25 | if location.FileId > a.FileId { 26 | return 1 27 | } 28 | if location.Offset < a.Offset { 29 | return -1 30 | } 31 | if location.Offset > a.Offset { 32 | return 1 33 | } 34 | return 0 35 | } 36 | 37 | func (location *Location) Distance(fileSize int64, backLocation *Location) int64 { 38 | return int64(backLocation.FileId-location.FileId)*fileSize + (backLocation.Offset - location.Offset) 39 | } 40 | 41 | func (location Location) String() string { 42 | return strconv.FormatUint(location.FileId, 10) + "-" + strconv.FormatInt(location.Offset, 10) 43 | } 44 | -------------------------------------------------------------------------------- /cmd/nodemanager/default_node_manager.go: -------------------------------------------------------------------------------- 1 | package nodemanager 2 | 3 | import ( 4 | "gopkg.in/urfave/cli.v1" 5 | 6 | "github.com/vitelabs/go-vite/v2/node" 7 | ) 8 | 9 | type DefaultNodeManager struct { 10 | ctx *cli.Context 11 | node *node.Node 12 | } 13 | 14 | func NewDefaultNodeManager(ctx *cli.Context, maker NodeMaker) (*DefaultNodeManager, error) { 15 | node, err := maker.MakeNode(ctx) 16 | if err != nil { 17 | return nil, err 18 | } 19 | return &DefaultNodeManager{ 20 | ctx: ctx, 21 | node: node, 22 | }, nil 23 | } 24 | 25 | func (nodeManager *DefaultNodeManager) Start() error { 26 | // 1: Start up the node 27 | err := StartNode(nodeManager.node) 28 | if err != nil { 29 | return err 30 | } 31 | 32 | // 2: Waiting for node to close 33 | WaitNode(nodeManager.node) 34 | 35 | return nil 36 | } 37 | 38 | func (nodeManager *DefaultNodeManager) Stop() error { 39 | 40 | StopNode(nodeManager.node) 41 | 42 | return nil 43 | } 44 | 45 | func (nodeManager *DefaultNodeManager) Node() *node.Node { 46 | 47 | return nodeManager.node 48 | } 49 | -------------------------------------------------------------------------------- /common/db/xleveldb/util/hash.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, Suryandaru Triandana 2 | // All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license that can be 5 | // found in the LICENSE file. 6 | 7 | package util 8 | 9 | import ( 10 | "encoding/binary" 11 | ) 12 | 13 | // Hash return hash of the given data. 14 | func Hash(data []byte, seed uint32) uint32 { 15 | // Similar to murmur hash 16 | const ( 17 | m = uint32(0xc6a4a793) 18 | r = uint32(24) 19 | ) 20 | var ( 21 | h = seed ^ (uint32(len(data)) * m) 22 | i int 23 | ) 24 | 25 | for n := len(data) - len(data)%4; i < n; i += 4 { 26 | h += binary.LittleEndian.Uint32(data[i:]) 27 | h *= m 28 | h ^= (h >> 16) 29 | } 30 | 31 | switch len(data) - i { 32 | default: 33 | panic("not reached") 34 | case 3: 35 | h += uint32(data[i+2]) << 16 36 | fallthrough 37 | case 2: 38 | h += uint32(data[i+1]) << 8 39 | fallthrough 40 | case 1: 41 | h += uint32(data[i]) 42 | h *= m 43 | h ^= (h >> r) 44 | case 0: 45 | } 46 | 47 | return h 48 | } 49 | -------------------------------------------------------------------------------- /conf/node_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "Identity": "foobar", 3 | "NetID": 1, 4 | "ListenInterface": "0.0.0.0", 5 | "Port": 8483, 6 | "FilePort": 8484, 7 | "MaxPeers": 10, 8 | "MinPeers": 5, 9 | "MaxInboundRatio": 2, 10 | "MaxPendingPeers": 5, 11 | "BootSeeds": [ 12 | "https://bootnodes.vite.net/bootmainnet.json" 13 | ], 14 | "Discover": true, 15 | "RPCEnabled": true, 16 | "HttpHost": "0.0.0.0", 17 | "HttpPort": 48132, 18 | "WSEnabled": false, 19 | "WSHost": "0.0.0.0", 20 | "WSPort": 41420, 21 | "HttpVirtualHosts": [], 22 | "IPCEnabled": true, 23 | "PublicModules": [ 24 | "ledger", 25 | "net", 26 | "contract", 27 | "util", 28 | "debug", 29 | "sbpstats", 30 | "dashboard" 31 | ], 32 | "Miner": false, 33 | "CoinBase": "", 34 | "EntropyStorePath": "", 35 | "EntropyStorePassword": "", 36 | "LogLevel": "info", 37 | "OpenPlugins": true, 38 | "SubscribeEnabled": true, 39 | "TxDexEnable": true, 40 | "VmLogAll": true, 41 | "DashboardTargetURL": "wss://stats.vite.net", 42 | "RewardAddr": "vite_xxxxxxxxxxxxxxxxxx" 43 | } -------------------------------------------------------------------------------- /ledger/chain/block/snapshot_block.go: -------------------------------------------------------------------------------- 1 | package chain_block 2 | 3 | import ( 4 | "fmt" 5 | 6 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 7 | chain_file_manager "github.com/vitelabs/go-vite/v2/ledger/chain/file_manager" 8 | ) 9 | 10 | // GetSnapshotBlock by location 11 | func (bDB *BlockDB) GetSnapshotBlock(location *chain_file_manager.Location) (*ledger.SnapshotBlock, error) { 12 | buf, err := bDB.Read(location) 13 | if err != nil { 14 | return nil, err 15 | } 16 | if len(buf) <= 0 { 17 | return nil, nil 18 | } 19 | sb := &ledger.SnapshotBlock{} 20 | if err := sb.Deserialize(buf); err != nil { 21 | return nil, fmt.Errorf("sb.Deserialize failed, Error: %s", err.Error()) 22 | } 23 | 24 | return sb, nil 25 | } 26 | 27 | // TODO optimize 28 | func (bDB *BlockDB) GetSnapshotHeader(location *chain_file_manager.Location) (*ledger.SnapshotBlock, error) { 29 | sb, err := bDB.GetSnapshotBlock(location) 30 | if err != nil { 31 | return nil, err 32 | } 33 | if sb == nil { 34 | return nil, nil 35 | } 36 | sb.SnapshotContent = nil 37 | return sb, nil 38 | } 39 | -------------------------------------------------------------------------------- /tools/circle/map.go: -------------------------------------------------------------------------------- 1 | package circle 2 | 3 | type TraverseFn = func(key Key, value Value) bool 4 | 5 | type Map interface { 6 | Get(key Key) (Value, bool) 7 | Put(key Key, value Value) 8 | Traverse(TraverseFn) 9 | Size() int 10 | } 11 | 12 | type circleMap struct { 13 | m map[Key]Value 14 | l List 15 | } 16 | 17 | func (cm *circleMap) Size() int { 18 | return cm.l.Size() 19 | } 20 | 21 | func (cm *circleMap) Traverse(fn TraverseFn) { 22 | cm.l.Traverse(func(key Key) bool { 23 | if v, ok := cm.m[key]; ok { 24 | return fn(key, v) 25 | } 26 | return true 27 | }) 28 | } 29 | 30 | func (cm *circleMap) Get(key Key) (Value, bool) { 31 | v, ok := cm.m[key] 32 | return v, ok 33 | } 34 | 35 | func (cm *circleMap) Put(key Key, value Value) { 36 | if _, ok := cm.m[key]; ok { 37 | cm.m[key] = value 38 | return 39 | } 40 | 41 | old := cm.l.Put(key) 42 | if old != nil { 43 | delete(cm.m, old) 44 | } 45 | cm.m[key] = value 46 | } 47 | 48 | func NewMap(total int) Map { 49 | return &circleMap{ 50 | m: make(map[Key]Value, total), 51 | l: NewList(total), 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /client/rpc.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | rpc2 "github.com/vitelabs/go-vite/v2/client/rpc" 5 | "github.com/vitelabs/go-vite/v2/rpc" 6 | ) 7 | 8 | type RpcClient interface { 9 | rpc2.LedgerApi 10 | rpc2.OnroadApi 11 | rpc2.TxApi 12 | rpc2.ContractApi 13 | rpc2.DexTradeApi 14 | rpc2.RandomApi 15 | 16 | GetClient() *rpc.Client 17 | } 18 | 19 | func NewRpcClient(rawurl string) (RpcClient, error) { 20 | c, err := rpc.Dial(rawurl) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | r := &rpcClient{ 26 | LedgerApi: rpc2.NewLedgerApi(c), 27 | OnroadApi: rpc2.NewOnroadApi(c), 28 | TxApi: rpc2.NewTxApi(c), 29 | ContractApi: rpc2.NewContractApi(c), 30 | DexTradeApi: rpc2.NewDexTradeApi(c), 31 | RandomApi: rpc2.NewRandomApi(c), 32 | cc: c, 33 | } 34 | return r, nil 35 | } 36 | 37 | type rpcClient struct { 38 | rpc2.LedgerApi 39 | rpc2.OnroadApi 40 | rpc2.TxApi 41 | rpc2.ContractApi 42 | rpc2.DexTradeApi 43 | rpc2.RandomApi 44 | 45 | cc *rpc.Client 46 | } 47 | 48 | func (c rpcClient) GetClient() *rpc.Client { 49 | return c.cc 50 | } 51 | -------------------------------------------------------------------------------- /cmd/updater/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | "github.com/syndtr/goleveldb/leveldb" 8 | 9 | "github.com/vitelabs/go-vite/v2/common/types" 10 | "github.com/vitelabs/go-vite/v2/ledger/consensus/cdb" 11 | ) 12 | 13 | var hash = flag.String("hash", "", "remove consensus result hash") 14 | var dir = flag.String("dataDir", "devdata", "data dir, for example: devdata") 15 | var delete = flag.Bool("delete", false, "delete ?") 16 | 17 | func main() { 18 | flag.Parse() 19 | db, err := leveldb.OpenFile(*dir, nil) 20 | 21 | if err != nil { 22 | panic(err) 23 | } 24 | 25 | hashPanic := types.HexToHashPanic(*hash) 26 | 27 | cDB := cdb.NewConsensusDB(db) 28 | addr, err := cDB.GetElectionResultByHash(hashPanic) 29 | if err != nil { 30 | panic(err) 31 | } 32 | 33 | fmt.Printf("addr send:%s\n", hashPanic) 34 | for k, v := range addr { 35 | fmt.Printf("%d\t%s\n", k, v) 36 | } 37 | if *delete { 38 | fmt.Printf("delete by hash:%s", hashPanic) 39 | err := cDB.DeleteElectionResultByHash(hashPanic) 40 | if err != nil { 41 | panic(err) 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /net/vnode/mock.go: -------------------------------------------------------------------------------- 1 | package vnode 2 | 3 | import ( 4 | crand "crypto/rand" 5 | mrand "math/rand" 6 | "net" 7 | ) 8 | 9 | func mockIP() (ip net.IP, typ HostType) { 10 | ipv4 := mrand.Intn(10) > 5 11 | if ipv4 { 12 | ip = make(net.IP, 4) 13 | typ = HostIPv4 14 | } else { 15 | ip = make(net.IP, 16) 16 | typ = HostIPv6 17 | } 18 | 19 | crand.Read(ip) 20 | return 21 | } 22 | 23 | func mockPort() int { 24 | return mrand.Intn(65535) 25 | } 26 | 27 | func mockRest() (ext []byte) { 28 | ext = make([]byte, mrand.Intn(1000)) 29 | 30 | crand.Read(ext) 31 | 32 | return 33 | } 34 | 35 | func mockNet() int { 36 | return mrand.Intn(1000) 37 | } 38 | 39 | func MockNode(domain bool, ext bool) *Node { 40 | n := &Node{ 41 | ID: RandomNodeID(), 42 | EndPoint: EndPoint{ 43 | Port: mockPort(), 44 | }, 45 | Net: mockNet(), 46 | Ext: nil, 47 | } 48 | 49 | if domain { 50 | n.EndPoint.Host = []byte("www.vite.org") 51 | n.EndPoint.Typ = HostDomain 52 | } else { 53 | n.EndPoint.Host, n.EndPoint.Typ = mockIP() 54 | } 55 | 56 | if ext { 57 | n.Ext = mockRest() 58 | } 59 | 60 | return n 61 | } 62 | -------------------------------------------------------------------------------- /cmd/utils/cli.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "gopkg.in/urfave/cli.v1" 5 | ) 6 | 7 | var ( 8 | CommandHelpTemplate = `{{.cmd.Name}}{{if .cmd.Subcommands}} command{{end}}{{if .cmd.Flags}} [command options]{{end}} [arguments...] 9 | {{if .cmd.Description}}{{.cmd.Description}} 10 | {{end}}{{if .cmd.Subcommands}} 11 | SUBCOMMANDS: 12 | {{range .cmd.Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}} 13 | {{end}}{{end}}{{if .categorizedFlags}} 14 | {{range $idx, $categorized := .categorizedFlags}}{{$categorized.Name}} OPTIONS: 15 | {{range $categorized.Flags}}{{"\t"}}{{.}} 16 | {{end}} 17 | {{end}}{{end}}` 18 | ) 19 | 20 | func init() { 21 | cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...] 22 | 23 | VERSION: 24 | {{.Version}} 25 | 26 | COMMANDS: 27 | {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}} 28 | {{end}}{{if .Flags}} 29 | GLOBAL OPTIONS: 30 | {{range .Flags}}{{.}} 31 | {{end}}{{end}} 32 | ` 33 | 34 | cli.CommandHelpTemplate = CommandHelpTemplate 35 | } 36 | -------------------------------------------------------------------------------- /cmd/subcmd_check_chain/check_chain.go: -------------------------------------------------------------------------------- 1 | package subcmd_check_chain 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "gopkg.in/urfave/cli.v1" 8 | 9 | "github.com/vitelabs/go-vite/v2/cmd/nodemanager" 10 | "github.com/vitelabs/go-vite/v2/cmd/utils" 11 | "github.com/vitelabs/go-vite/v2/log15" 12 | ) 13 | 14 | var ( 15 | checkChainCommand = cli.Command{ 16 | Action: utils.MigrateFlags(checkChainAction), 17 | Name: "checkChain", 18 | Usage: "checkChain", 19 | Category: "CHECK CHAIN COMMANDS", 20 | Flags: utils.ConfigFlags, 21 | Description: ` 22 | check chain 23 | `, 24 | } 25 | log = log15.New("module", "gvite/export") 26 | ) 27 | 28 | func checkChainAction(ctx *cli.Context) error { 29 | // Create and start the node based on the CLI flags 30 | nodeManager, err := nodemanager.NewCheckChainNodeManager(ctx, nodemanager.FullNodeMaker{}) 31 | if err != nil { 32 | log.Error(fmt.Sprintf("new Node error, %+v", err)) 33 | return err 34 | } 35 | if err := nodeManager.Start(); err != nil { 36 | log.Error(err.Error()) 37 | fmt.Println(err.Error()) 38 | return err 39 | } 40 | 41 | os.Exit(0) 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /interfaces/core/account.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "github.com/golang/protobuf/proto" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | "github.com/vitelabs/go-vite/v2/common/vitepb" 8 | "github.com/vitelabs/go-vite/v2/crypto/ed25519" 9 | ) 10 | 11 | type Account struct { 12 | AccountAddress types.Address 13 | AccountId uint64 14 | PublicKey ed25519.PublicKey 15 | } 16 | 17 | func (account *Account) Proto() *vitepb.Account { 18 | pb := &vitepb.Account{} 19 | pb.AccountId = account.AccountId 20 | pb.PublicKey = account.PublicKey 21 | return pb 22 | } 23 | 24 | func (account *Account) DeProto(pb *vitepb.Account) { 25 | account.AccountId = pb.AccountId 26 | account.PublicKey = pb.PublicKey 27 | account.AccountAddress, _ = types.BytesToAddress(pb.PublicKey) 28 | } 29 | 30 | func (account *Account) Serialize() ([]byte, error) { 31 | return proto.Marshal(account.Proto()) 32 | } 33 | 34 | func (account *Account) Deserialize(buf []byte) error { 35 | pb := &vitepb.Account{} 36 | if err := proto.Unmarshal(buf, pb); err != nil { 37 | return err 38 | } 39 | account.DeProto(pb) 40 | return nil 41 | } 42 | -------------------------------------------------------------------------------- /common/mock.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | ) 9 | 10 | func MockAddress(i int) types.Address { 11 | base := "0000000000000000000fff" + fmt.Sprintf("%0*d", 6, i) + "fff00000000000" 12 | bytes, _ := hex.DecodeString(base) 13 | addresses, _ := types.BytesToAddress(bytes) 14 | return addresses 15 | } 16 | 17 | func MockHash(i int) types.Hash { 18 | base := "0000000000000000000000000000fff" + fmt.Sprintf("%0*d", 6, i) + "fff000000000000000000000000" 19 | bytes, err := hex.DecodeString(base) 20 | if err != nil { 21 | panic(err) 22 | } 23 | addresses, err := types.BytesToHash(bytes) 24 | if err != nil { 25 | panic(err) 26 | } 27 | return addresses 28 | } 29 | 30 | func MockHashBy(i1 int, i int) types.Hash { 31 | base := fmt.Sprintf("%0*d", 6, i1) + "0000000000000000000000fff" + fmt.Sprintf("%0*d", 6, i) + "fff000000000000000000000000" 32 | bytes, err := hex.DecodeString(base) 33 | if err != nil { 34 | panic(err) 35 | } 36 | addresses, err := types.BytesToHash(bytes) 37 | if err != nil { 38 | panic(err) 39 | } 40 | return addresses 41 | } 42 | -------------------------------------------------------------------------------- /interfaces/generator.go: -------------------------------------------------------------------------------- 1 | package interfaces 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | "github.com/vitelabs/go-vite/v2/interfaces/core" 8 | ) 9 | 10 | // GenResult represents the result of a block being validated by vm. 11 | type GenResult struct { 12 | VMBlock *VmAccountBlock 13 | IsRetry bool 14 | Err error 15 | } 16 | 17 | // IncomingMessage carries the necessary transaction info. 18 | type IncomingMessage struct { 19 | BlockType byte 20 | 21 | AccountAddress types.Address 22 | ToAddress *types.Address 23 | FromBlockHash *types.Hash 24 | 25 | TokenId *types.TokenTypeId 26 | Amount *big.Int 27 | Fee *big.Int 28 | Data []byte 29 | 30 | Difficulty *big.Int 31 | } 32 | 33 | type Generator interface { 34 | GenerateWithBlock(block *core.AccountBlock, fromBlock *core.AccountBlock) (*GenResult, error) 35 | GenerateWithMessage(message *IncomingMessage, producer *types.Address, signFunc SignFunc) (*GenResult, error) 36 | GenerateWithOnRoad(sendBlock *core.AccountBlock, producer *types.Address, signFunc SignFunc, difficulty *big.Int) (*GenResult, error) 37 | GetVMDB() VmDb 38 | } 39 | -------------------------------------------------------------------------------- /ledger/chain/cache/cache.go: -------------------------------------------------------------------------------- 1 | package chain_cache 2 | 3 | import ( 4 | "sync" 5 | 6 | "github.com/vitelabs/go-vite/v2/interfaces" 7 | ) 8 | 9 | type Cache struct { 10 | chain Chain 11 | 12 | ds *dataSet 13 | mu sync.RWMutex 14 | 15 | unconfirmedPool *UnconfirmedPool 16 | hd *hotData 17 | quotaList *quotaList 18 | } 19 | 20 | func NewCache(chain Chain) (*Cache, error) { 21 | ds := NewDataSet() 22 | c := &Cache{ 23 | ds: ds, 24 | chain: chain, 25 | 26 | unconfirmedPool: NewUnconfirmedPool(ds), 27 | hd: newHotData(ds), 28 | quotaList: newQuotaList(chain), 29 | } 30 | 31 | return c, nil 32 | } 33 | 34 | func (cache *Cache) Destroy() { 35 | cache.mu.Lock() 36 | defer cache.mu.Unlock() 37 | 38 | cache.ds.Close() 39 | cache.ds = nil 40 | cache.unconfirmedPool = nil 41 | cache.hd = nil 42 | } 43 | 44 | func (cache *Cache) GetStatus() []interfaces.DBStatus { 45 | dsCacheStatus := cache.ds.GetStatus() 46 | 47 | return []interfaces.DBStatus{{ 48 | Name: "blockCache.ds.cache", 49 | Count: dsCacheStatus[0].Count, 50 | Size: dsCacheStatus[0].Size, 51 | Status: "", 52 | }} 53 | } 54 | -------------------------------------------------------------------------------- /ledger/pool/lock/chain_lock.go: -------------------------------------------------------------------------------- 1 | package lock 2 | 3 | import "sync" 4 | 5 | type ChainRollback interface { 6 | RLockRollback() 7 | RUnLockRollback() 8 | LockRollback() 9 | UnLockRollback() 10 | } 11 | 12 | type ChainInsert interface { 13 | RLockInsert() 14 | RUnLockInsert() 15 | LockInsert() 16 | UnLockInsert() 17 | } 18 | 19 | type EasyImpl struct { 20 | chainInsertRw sync.RWMutex 21 | chainRollbackRw sync.RWMutex 22 | } 23 | 24 | func (self *EasyImpl) RLockInsert() { 25 | self.chainInsertRw.RLock() 26 | } 27 | 28 | func (self *EasyImpl) RUnLockInsert() { 29 | self.chainInsertRw.RUnlock() 30 | } 31 | 32 | func (self *EasyImpl) LockInsert() { 33 | self.chainInsertRw.Lock() 34 | } 35 | 36 | func (self *EasyImpl) UnLockInsert() { 37 | self.chainInsertRw.Unlock() 38 | } 39 | 40 | func (self *EasyImpl) RLockRollback() { 41 | self.chainRollbackRw.RLock() 42 | } 43 | 44 | func (self *EasyImpl) RUnLockRollback() { 45 | self.chainRollbackRw.RUnlock() 46 | } 47 | 48 | func (self *EasyImpl) LockRollback() { 49 | self.chainRollbackRw.Lock() 50 | } 51 | 52 | func (self *EasyImpl) UnLockRollback() { 53 | self.chainRollbackRw.Unlock() 54 | } 55 | -------------------------------------------------------------------------------- /cmd/subcmd_plugin_data/plugin_data_cmd.go: -------------------------------------------------------------------------------- 1 | package subcmd_plugin_data 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "gopkg.in/urfave/cli.v1" 8 | 9 | "github.com/vitelabs/go-vite/v2/cmd/nodemanager" 10 | "github.com/vitelabs/go-vite/v2/cmd/utils" 11 | "github.com/vitelabs/go-vite/v2/log15" 12 | ) 13 | 14 | var ( 15 | PluginDataCommand = cli.Command{ 16 | Action: utils.MigrateFlags(pluginDataAction), 17 | Name: "pluginData", 18 | Usage: "pluginData", 19 | Category: "PLUGIN DATA COMMANDS", 20 | Flags: utils.ConfigFlags, 21 | Description: ` 22 | recreate plugin data. 23 | `, 24 | } 25 | log = log15.New("module", "gvite/plugin_data") 26 | ) 27 | 28 | func pluginDataAction(ctx *cli.Context) error { 29 | // Create and start the node based on the CLI flags 30 | nodeManager, err := nodemanager.NewPluginDataNodeManager(ctx, nodemanager.FullNodeMaker{}) 31 | if err != nil { 32 | log.Error(fmt.Sprintf("new Node error, %+v", err)) 33 | return err 34 | } 35 | if err := nodeManager.Start(); err != nil { 36 | log.Error(err.Error()) 37 | fmt.Println(err.Error()) 38 | return err 39 | } 40 | 41 | os.Exit(0) 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /cmd/subcmd_export/export.go: -------------------------------------------------------------------------------- 1 | package subcmd_export 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "gopkg.in/urfave/cli.v1" 8 | 9 | "github.com/vitelabs/go-vite/v2/cmd/nodemanager" 10 | "github.com/vitelabs/go-vite/v2/cmd/utils" 11 | "github.com/vitelabs/go-vite/v2/log15" 12 | ) 13 | 14 | var ( 15 | ExportCommand = cli.Command{ 16 | Action: utils.MigrateFlags(exportLedgerAction), 17 | Name: "export", 18 | Usage: "export --sbHeight=5000000", 19 | Flags: append(utils.ExportFlags, utils.ConfigFlags...), 20 | Category: "EXPORT COMMANDS", 21 | Description: ` 22 | Export ledger. 23 | `, 24 | } 25 | log = log15.New("module", "gvite/export") 26 | ) 27 | 28 | func exportLedgerAction(ctx *cli.Context) error { 29 | // Create and start the node based on the CLI flags 30 | nodeManager, err := nodemanager.NewExportNodeManager(ctx, nodemanager.FullNodeMaker{}) 31 | if err != nil { 32 | log.Error(fmt.Sprintf("new Node error, %+v", err)) 33 | return err 34 | } 35 | 36 | if err := nodeManager.Start(); err != nil { 37 | log.Error(err.Error()) 38 | fmt.Println(err.Error()) 39 | return err 40 | } 41 | 42 | os.Exit(0) 43 | return nil 44 | } 45 | -------------------------------------------------------------------------------- /log15/term/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Simon Eskildsen 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 13 | all 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 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /log15/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Aaron L 2 | Alan Shreve 3 | Andy Walker 4 | Andy Watson 5 | Carl Veazey 6 | Chris Hines 7 | Christoph Hack 8 | Ciaran Downey 9 | Dmitry Chestnykh 10 | Evan Shaw 11 | Gonzalo Serrano 12 | Jeremy 13 | Jonathan Rudenberg 14 | Kang Seong-Min 15 | Kevin Burke 16 | Marc Abramowitz 17 | Nathan Baulch 18 | NotZippy 19 | Péter Szilágyi 20 | Robert Egorov 21 | Robert Starbuck 22 | Robert Zaremba 23 | Sean Chittenden 24 | Spencer Nelson 25 | Tomasz Grodzki 26 | Trevor Gattis 27 | Vincent Vanackere 28 | Will McGovern 29 | -------------------------------------------------------------------------------- /ledger/pool/batch/mock_chain.go: -------------------------------------------------------------------------------- 1 | package batch 2 | 3 | import ( 4 | "github.com/pkg/errors" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | var empty types.Hash 10 | 11 | func newMockChain() *mockChain { 12 | return &mockChain{all: make(map[types.Hash]struct{})} 13 | } 14 | 15 | type mockChain struct { 16 | all map[types.Hash]struct{} 17 | } 18 | 19 | func (mc mockChain) len() int { 20 | return len(mc.all) 21 | } 22 | 23 | func (mc mockChain) exists(hash types.Hash) error { 24 | if hash == empty { 25 | return nil 26 | } 27 | _, ok := mc.all[hash] 28 | if ok { 29 | return nil 30 | } 31 | return errors.New("not exists") 32 | } 33 | 34 | func (mc *mockChain) insert(item Item) error { 35 | keys, _, _ := item.ReferHashes() 36 | for _, v := range keys { 37 | _, ok := mc.all[v] 38 | if ok { 39 | return errors.Errorf("exist for hash[%s]", v) 40 | } 41 | mc.all[v] = struct{}{} 42 | } 43 | return nil 44 | } 45 | 46 | func (mc *mockChain) execute(p Batch, l Level, bucket Bucket, version uint64) error { 47 | for _, v := range bucket.Items() { 48 | err := mc.insert(v) 49 | if err != nil { 50 | return err 51 | } 52 | } 53 | return nil 54 | } 55 | -------------------------------------------------------------------------------- /cmd/subcmd_recover/subcmd_recover.go: -------------------------------------------------------------------------------- 1 | package subcmd_recover 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "gopkg.in/urfave/cli.v1" 8 | 9 | "github.com/vitelabs/go-vite/v2/cmd/nodemanager" 10 | "github.com/vitelabs/go-vite/v2/cmd/utils" 11 | "github.com/vitelabs/go-vite/v2/log15" 12 | ) 13 | 14 | var ( 15 | LedgerRecoverCommand = cli.Command{ 16 | Action: utils.MigrateFlags(recoverLedgerAction), 17 | Name: "recover", 18 | Usage: "recover --del=500000", 19 | ArgsUsage: "--del=500000", 20 | Flags: append(utils.LedgerFlags, utils.ConfigFlags...), 21 | Category: "RECOVER COMMANDS", 22 | Description: ` 23 | Recover ledger. 24 | `, 25 | } 26 | log = log15.New("module", "gvite/recover") 27 | ) 28 | 29 | func recoverLedgerAction(ctx *cli.Context) error { 30 | // Create and start the node based on the CLI flags 31 | nodeManager, err := nodemanager.NewRecoverNodeManager(ctx, nodemanager.FullNodeMaker{}) 32 | if err != nil { 33 | log.Error(fmt.Sprintf("new Node error, %+v", err)) 34 | return err 35 | } 36 | if err := nodeManager.Start(); err != nil { 37 | log.Error(err.Error()) 38 | fmt.Println(err.Error()) 39 | return err 40 | } 41 | os.Exit(0) 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /common/condTimer.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "sync" 5 | "sync/atomic" 6 | "time" 7 | ) 8 | 9 | type CondTimer struct { 10 | cd *sync.Cond 11 | notifyNum uint32 12 | closed chan struct{} 13 | } 14 | 15 | func NewCondTimer() *CondTimer { 16 | mutex := &sync.Mutex{} 17 | return &CondTimer{cd: sync.NewCond(mutex), closed: make(chan struct{})} 18 | } 19 | 20 | func (self *CondTimer) Wait() { 21 | old := atomic.SwapUint32(&self.notifyNum, 0) 22 | if old > 0 { 23 | return 24 | } 25 | self.cd.L.Lock() 26 | defer self.cd.L.Unlock() 27 | self.cd.Wait() 28 | } 29 | 30 | func (self *CondTimer) Broadcast() { 31 | atomic.AddUint32(&self.notifyNum, 1) 32 | self.cd.Broadcast() 33 | } 34 | 35 | func (self *CondTimer) Signal() { 36 | atomic.AddUint32(&self.notifyNum, 1) 37 | self.cd.Signal() 38 | } 39 | 40 | func (self *CondTimer) Start(t time.Duration) { 41 | go func() { 42 | ticker := time.NewTicker(t) 43 | defer ticker.Stop() 44 | for { 45 | select { 46 | case <-self.closed: 47 | return 48 | case <-ticker.C: 49 | self.cd.Broadcast() 50 | } 51 | } 52 | }() 53 | } 54 | 55 | func (self *CondTimer) Stop() { 56 | close(self.closed) 57 | self.Broadcast() 58 | } 59 | -------------------------------------------------------------------------------- /ledger/consensus/consensus_simple_test.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/stretchr/testify/assert" 8 | 9 | "github.com/vitelabs/go-vite/v2/log15" 10 | ) 11 | 12 | func TestSimpleCs(t *testing.T) { 13 | cs := newSimpleCs(log15.New("unitest", "simpleCs")) 14 | 15 | info := cs.GroupInfo 16 | stime, etime := cs.Index2Time(0) 17 | // genesis 18 | assert.True(t, stime.Unix() == simpleGenesis.Unix()) 19 | // plan interval 20 | assert.Equal(t, stime.Add(time.Duration(info.PlanInterval)*time.Second), etime) 21 | 22 | result, err := cs.ElectionIndex(0) 23 | assert.Nil(t, err) 24 | 25 | for k, v := range result.Plans { 26 | assert.Equal(t, simpleAddrs[k/3], v.Member) 27 | } 28 | 29 | result, err = cs.ElectionIndex(1) 30 | assert.Nil(t, err) 31 | 32 | for k, v := range result.Plans { 33 | assert.Equal(t, simpleAddrs[k/3], v.Member) 34 | } 35 | 36 | stime, _ = cs.Index2Time(1) 37 | eleTime, err := cs.ElectionTime(stime) 38 | eleIndex, err := cs.ElectionIndex(1) 39 | 40 | for k, v := range eleIndex.Plans { 41 | assert.Equal(t, eleTime.Plans[k], v) 42 | } 43 | 44 | assert.Equal(t, uint64(0), cs.Time2Index(simpleGenesis.Add(time.Second))) 45 | } 46 | -------------------------------------------------------------------------------- /common/lifecycle.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "sync/atomic" 5 | ) 6 | 7 | type LifecycleStatus struct { 8 | Status int32 // 0:origin 1: initing 2:inited 3:starting 4:started 5:stopping 6:stopped 9 | } 10 | 11 | func (self *LifecycleStatus) PreInit() bool { 12 | return atomic.CompareAndSwapInt32(&self.Status, 0, 1) 13 | } 14 | func (self *LifecycleStatus) PostInit() bool { 15 | return atomic.CompareAndSwapInt32(&self.Status, 1, 2) 16 | } 17 | func (self *LifecycleStatus) PreStart() bool { 18 | return atomic.CompareAndSwapInt32(&self.Status, 2, 3) 19 | } 20 | func (self *LifecycleStatus) PostStart() bool { 21 | return atomic.CompareAndSwapInt32(&self.Status, 3, 4) 22 | } 23 | func (self *LifecycleStatus) PreStop() bool { 24 | return atomic.CompareAndSwapInt32(&self.Status, 4, 5) 25 | } 26 | func (self *LifecycleStatus) PostStop() bool { 27 | return atomic.CompareAndSwapInt32(&self.Status, 5, 6) 28 | } 29 | 30 | func (self *LifecycleStatus) Stopped() bool { 31 | return self.Status == 6 || self.Status == 5 32 | } 33 | func (self *LifecycleStatus) GetStatus() int32 { 34 | return self.Status 35 | } 36 | 37 | type Lifecycle interface { 38 | Init() 39 | Start() 40 | Stop() 41 | GetStatus() int32 42 | } 43 | -------------------------------------------------------------------------------- /client/rpc/tx.go: -------------------------------------------------------------------------------- 1 | // 2 | 3 | package rpc 4 | 5 | import ( 6 | "github.com/vitelabs/go-vite/v2/rpc" 7 | "github.com/vitelabs/go-vite/v2/rpcapi/api" 8 | ) 9 | 10 | // TxApi ... 11 | type TxApi interface { 12 | SendRawTx(block *api.AccountBlock) error 13 | SendTxWithPrivateKey(param api.SendTxWithPrivateKeyParam) (*api.AccountBlock, error) 14 | CalcPoWDifficulty(param api.CalcPoWDifficultyParam) (result *api.CalcPoWDifficultyResult, err error) 15 | } 16 | 17 | type txApi struct { 18 | cc *rpc.Client 19 | } 20 | 21 | func NewTxApi(cc *rpc.Client) TxApi { 22 | return &txApi{cc: cc} 23 | } 24 | 25 | func (ti txApi) SendRawTx(block *api.AccountBlock) (err error) { 26 | err = ti.cc.Call(nil, "tx_sendRawTx", block) 27 | return 28 | } 29 | 30 | func (ti txApi) SendTxWithPrivateKey(param api.SendTxWithPrivateKeyParam) (block *api.AccountBlock, err error) { 31 | block = &api.AccountBlock{} 32 | err = ti.cc.Call(block, "tx_sendTxWithPrivateKey", param) 33 | return 34 | } 35 | 36 | func (ti txApi) CalcPoWDifficulty(param api.CalcPoWDifficultyParam) (result *api.CalcPoWDifficultyResult, err error) { 37 | result = &api.CalcPoWDifficultyResult{} 38 | err = ti.cc.Call(result, "tx_calcPoWDifficulty", param) 39 | return 40 | } 41 | -------------------------------------------------------------------------------- /rpcapi/api/virtual.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/vitelabs/go-vite/v2" 7 | "github.com/vitelabs/go-vite/v2/common/upgrade" 8 | "github.com/vitelabs/go-vite/v2/ledger/chain" 9 | "github.com/vitelabs/go-vite/v2/ledger/consensus" 10 | ) 11 | 12 | type VirtualApi struct { 13 | vite *vite.Vite 14 | chain chain.Chain 15 | cs consensus.Consensus 16 | } 17 | 18 | func NewVirtualApi(vite *vite.Vite) *VirtualApi { 19 | return &VirtualApi{ 20 | vite: vite, 21 | chain: vite.Chain(), 22 | cs: vite.Consensus(), 23 | } 24 | } 25 | 26 | func (api VirtualApi) String() string { 27 | return "VirtualApi" 28 | } 29 | 30 | func (api *VirtualApi) Mine() error { 31 | return api.vite.Producer().SnapshotOnce() 32 | } 33 | 34 | func (api *VirtualApi) MineBatch(number uint64) error { 35 | if number > 1000 { 36 | return errors.New("number must be less than 1000") 37 | } 38 | 39 | for i := uint64(0); i < number; i++ { 40 | err := api.vite.Producer().SnapshotOnce() 41 | if err != nil { 42 | return err 43 | } 44 | } 45 | return nil 46 | } 47 | 48 | func (api *VirtualApi) AddUpgrade(version uint32, height uint64) error { 49 | return upgrade.AddUpgradePoint(version, height) 50 | } 51 | -------------------------------------------------------------------------------- /ledger/pool/tools.go: -------------------------------------------------------------------------------- 1 | package pool 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | "github.com/vitelabs/go-vite/v2/net" 8 | ) 9 | 10 | type tools struct { 11 | // if address == nil, snapshot tools 12 | // else account fetcher 13 | fetcher commonSyncer 14 | rw chainRw 15 | } 16 | 17 | func newTools(f commonSyncer, rw chainRw) *tools { 18 | self := &tools{} 19 | self.fetcher = f 20 | self.rw = rw 21 | return self 22 | } 23 | 24 | type syncer interface { 25 | net.Broadcaster 26 | net.Fetcher 27 | net.Subscriber 28 | net.ChunkReader 29 | } 30 | 31 | type fetchRequest struct { 32 | snapshot bool 33 | chain *types.Address 34 | hash types.Hash 35 | accHeight uint64 36 | prevCnt uint64 37 | snapshotHash *types.Hash 38 | snapshotHeight uint64 39 | } 40 | 41 | func (request *fetchRequest) String() string { 42 | if request.chain == nil { 43 | return strconv.FormatBool(request.snapshot) + "," + request.hash.String() + "," + strconv.FormatUint(request.prevCnt, 10) 44 | } 45 | return strconv.FormatBool(request.snapshot) + "," + request.hash.String() + "," + strconv.FormatUint(request.prevCnt, 10) + request.chain.String() + "," 46 | } 47 | -------------------------------------------------------------------------------- /ledger/pool/batch/level_account.go: -------------------------------------------------------------------------------- 1 | package batch 2 | 3 | import ( 4 | "github.com/pkg/errors" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ) 8 | 9 | type accountLevel struct { 10 | level 11 | bs map[types.Address]*bucket 12 | sHash *types.Hash 13 | } 14 | 15 | func (self *accountLevel) Buckets() (result []Bucket) { 16 | for _, v := range self.bs { 17 | result = append(result, v) 18 | } 19 | return 20 | } 21 | 22 | func newAccountLevel(index int, sHash *types.Hash) *accountLevel { 23 | return &accountLevel{bs: make(map[types.Address]*bucket), level: level{index: index}, sHash: sHash} 24 | } 25 | 26 | func (self *accountLevel) Snapshot() bool { 27 | return false 28 | } 29 | 30 | func (self *accountLevel) SHash() *types.Hash { 31 | return self.sHash 32 | } 33 | 34 | func (self *accountLevel) Add(b Item) error { 35 | if self.Closed() { 36 | panic(errors.New("level is closed")) 37 | } 38 | owner := *b.Owner() 39 | _, ok := self.bs[owner] 40 | if !ok { 41 | self.bs[owner] = newBucket(&owner) 42 | } 43 | return self.bs[owner].add(b) 44 | } 45 | 46 | func (self *accountLevel) Size() int { 47 | num := 0 48 | for _, v := range self.bs { 49 | num += len(v.Items()) 50 | } 51 | 52 | return num 53 | } 54 | -------------------------------------------------------------------------------- /ledger/chain/test_tools/mock.go: -------------------------------------------------------------------------------- 1 | package test_tools 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/golang/mock/gomock" 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | "github.com/vitelabs/go-vite/v2/interfaces" 9 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 10 | "github.com/vitelabs/go-vite/v2/ledger/consensus/core" 11 | ) 12 | 13 | func NewPeriodTimeIndex(genesisTime *time.Time) interfaces.TimeIndex { 14 | genesis := time.Unix(genesisTime.Unix(), 0) 15 | ti := core.NewTimeIndex(genesis, time.Second*75) 16 | return ti 17 | } 18 | 19 | func NewSbpStatReader(ctrl *gomock.Controller) *core.MockSBPStatReader { 20 | return core.NewMockSBPStatReader(ctrl) 21 | } 22 | 23 | func NewVerifier() interfaces.ConsensusVerifier { 24 | return &MockCssVerifier{} 25 | } 26 | 27 | type MockCssVerifier struct{} 28 | 29 | func (c *MockCssVerifier) VerifyABsProducer(abs map[types.Gid][]*ledger.AccountBlock) ([]*ledger.AccountBlock, error) { 30 | return nil, nil 31 | } 32 | 33 | func (c *MockCssVerifier) VerifySnapshotProducer(block *ledger.SnapshotBlock) (bool, error) { 34 | return true, nil 35 | } 36 | 37 | func (c *MockCssVerifier) VerifyAccountProducer(block *ledger.AccountBlock) (bool, error) { 38 | return true, nil 39 | } 40 | -------------------------------------------------------------------------------- /tools/circle/map_test.go: -------------------------------------------------------------------------------- 1 | package circle 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestCircleMap_Size(t *testing.T) { 9 | const total = 5 10 | cm := NewMap(total) 11 | 12 | for i, j := 1, 10; i < total; i, j = i+1, j+1 { 13 | cm.Put(i, j) 14 | if cm.Size() != i { 15 | t.Fail() 16 | } 17 | } 18 | 19 | for i, j := 10, 10; i < total; i, j = i+1, j+1 { 20 | cm.Put(i, j) 21 | if cm.Size() != total { 22 | t.Fail() 23 | } 24 | } 25 | } 26 | 27 | func TestCircleMap_Get(t *testing.T) { 28 | 29 | } 30 | 31 | func TestCircleMap_Traverse(t *testing.T) { 32 | const total = 5 33 | cm := NewMap(total) 34 | 35 | for i, j := 1, 10; i < total; i, j = i+1, j+1 { 36 | cm.Put(i, j) 37 | } 38 | 39 | k, v := 1, 10 40 | cm.Traverse(func(key Key, value Value) bool { 41 | fmt.Println(key, value) 42 | if key != k || value != v { 43 | t.Fail() 44 | } 45 | k++ 46 | v++ 47 | return true 48 | }) 49 | 50 | for i, j := 5, 10; i < 10; i, j = i+1, j+1 { 51 | cm.Put(i, j) 52 | } 53 | k, v = 5, 10 54 | cm.Traverse(func(key Key, value Value) bool { 55 | if key != k || value != v { 56 | t.Fail() 57 | } 58 | k++ 59 | v++ 60 | return true 61 | }) 62 | 63 | if k != 10 || v != 15 { 64 | t.Fail() 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /common/types/quota.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | type QuotaInfo struct { 4 | BlockCount uint64 5 | QuotaTotal uint64 6 | QuotaUsedTotal uint64 7 | } 8 | 9 | type Quota struct { 10 | current uint64 11 | stakeQuotaPerSnapshotBlock uint64 12 | avg uint64 13 | snapshotCurrent uint64 14 | blocked bool 15 | blockReleaseHeight uint64 16 | } 17 | 18 | func NewQuota(stakeQuota, current, avg, snapshotCurrent uint64, blocked bool, blockReleaseHeight uint64) Quota { 19 | return Quota{current, stakeQuota, avg, snapshotCurrent, blocked, blockReleaseHeight} 20 | } 21 | 22 | func (q *Quota) StakeQuotaPerSnapshotBlock() uint64 { 23 | return q.stakeQuotaPerSnapshotBlock 24 | } 25 | 26 | // Current quota of a single account 27 | func (q *Quota) Current() uint64 { 28 | return q.current 29 | } 30 | 31 | // Available quota in current snapshot block, excluding unconfirmed blocks 32 | func (q *Quota) SnapshotCurrent() uint64 { 33 | return q.snapshotCurrent 34 | } 35 | 36 | func (q *Quota) Avg() uint64 { 37 | return q.avg 38 | } 39 | 40 | func (q *Quota) Blocked() bool { 41 | return q.blocked 42 | } 43 | 44 | func (q *Quota) BlockReleaseHeight() uint64 { 45 | return q.blockReleaseHeight 46 | } 47 | -------------------------------------------------------------------------------- /ledger/chain/state/transform_iterator.go: -------------------------------------------------------------------------------- 1 | package chain_state 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/db/xleveldb/iterator" 5 | ) 6 | 7 | type TransformIterator struct { 8 | iter iterator.Iterator 9 | keyPrefixLength int 10 | } 11 | 12 | func NewTransformIterator(iter iterator.Iterator, keyPrefixLength int) *TransformIterator { 13 | return &TransformIterator{ 14 | iter: iter, 15 | keyPrefixLength: keyPrefixLength, 16 | } 17 | } 18 | 19 | func (rcIter *TransformIterator) Last() bool { 20 | return rcIter.iter.Last() 21 | } 22 | 23 | func (rcIter *TransformIterator) Prev() bool { 24 | return rcIter.iter.Prev() 25 | } 26 | 27 | func (rcIter *TransformIterator) Seek(key []byte) bool { 28 | return rcIter.iter.Seek(key) 29 | } 30 | 31 | func (rcIter *TransformIterator) Next() bool { 32 | return rcIter.iter.Next() 33 | } 34 | 35 | func (rcIter *TransformIterator) Key() []byte { 36 | return rcIter.iter.Key()[rcIter.keyPrefixLength:] 37 | } 38 | 39 | func (rcIter *TransformIterator) Value() []byte { 40 | return rcIter.iter.Value() 41 | } 42 | 43 | func (rcIter *TransformIterator) Error() error { 44 | return rcIter.iter.Error() 45 | } 46 | 47 | func (rcIter *TransformIterator) Release() { 48 | rcIter.iter.Release() 49 | } 50 | -------------------------------------------------------------------------------- /ledger/pool/tree/printer.go: -------------------------------------------------------------------------------- 1 | package tree 2 | 3 | import "encoding/json" 4 | 5 | func PrintTree(b Tree) map[string]interface{} { 6 | result := make(map[string]interface{}) 7 | var branchInfos []map[string]interface{} 8 | for _, v := range b.Branches() { 9 | branchInfos = append(branchInfos, PrintBranchInfo(v)) 10 | } 11 | result["branches"] = branchInfos 12 | return result 13 | } 14 | 15 | func PrintTreeJson(b Tree) string { 16 | result := make(map[string]interface{}) 17 | var branchInfos []map[string]interface{} 18 | for _, v := range b.Branches() { 19 | branchInfos = append(branchInfos, PrintBranchInfo(v)) 20 | } 21 | result["branches"] = branchInfos 22 | bytes, _ := json.Marshal(result) 23 | return string(bytes) 24 | } 25 | 26 | func PrintBranchInfo(b Branch) map[string]interface{} { 27 | result := make(map[string]interface{}) 28 | result["Id"] = b.ID() 29 | if b.Type() == Normal { 30 | result["Head"] = b.SprintHead() 31 | result["Tail"] = b.SprintTail() 32 | result["Root"] = b.Root().ID() 33 | var children []string 34 | for _, v := range b.(*branch).allChildren() { 35 | children = append(children, v.ID()) 36 | } 37 | result["Children"] = children 38 | } else { 39 | result["Head"] = b.SprintHead() 40 | } 41 | return result 42 | } 43 | -------------------------------------------------------------------------------- /common/types/tokentypeid_test.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | CorrectTTI = "tti_2445f6e5cde8c2c70e446c83" 10 | WrongTTICheckSum = "tti_2445f6e5cde8c2c70e446c84" 11 | WrongTTIMain = "tti_2445f6e5cae8c2c70e446c83" 12 | WrongTTILen = "tti_2445f6e5cae8c2c70e446c8" 13 | WrongTTIPre = "1tti_2445f6e5cae8c2c70e446c" 14 | ) 15 | 16 | func TestCreateTokenTypeId(b *testing.T) { 17 | fmt.Println(CreateTokenTypeId([]byte{1, 1, 2}, []byte{1, 2}, []byte{1, 5})) 18 | } 19 | 20 | func TestHexToTokenTypeId(t *testing.T) { 21 | tti, err := HexToTokenTypeId(CorrectTTI) 22 | if err != nil || tti.Hex() != CorrectTTI { 23 | t.Fatal("expect correct but wrong") 24 | } 25 | 26 | _, err = HexToTokenTypeId(WrongTTICheckSum) 27 | if err == nil { 28 | t.Fatal("WrongTTICheckSum expect wrong but correct") 29 | } 30 | 31 | _, err = HexToTokenTypeId(WrongTTIMain) 32 | if err == nil { 33 | t.Fatal("WrongTTIMain expect wrong but correct") 34 | } 35 | 36 | _, err = HexToTokenTypeId(WrongTTILen) 37 | if err == nil { 38 | t.Fatal("WrongTTILen expect wrong but correct") 39 | } 40 | 41 | _, err = HexToTokenTypeId(WrongTTIPre) 42 | if err == nil { 43 | t.Fatal("WrongTTIPre expect wrong but correct") 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /cmd/printer/blocks/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "fmt" 7 | 8 | "github.com/vitelabs/go-vite/v2/common/helper" 9 | chain_block "github.com/vitelabs/go-vite/v2/ledger/chain/block" 10 | chain_file_manager "github.com/vitelabs/go-vite/v2/ledger/chain/file_manager" 11 | ) 12 | 13 | // env GOOS=linux GOARCH=amd64 go build -i -o blocks_printer ./cmd/printer/blocks/main.go 14 | var fieldId = flag.Uint64("fieldId", 1, "filed id") 15 | var offset = flag.Int64("offset", 0, "offset") 16 | 17 | var dir = flag.String("dataDir", "devdata", "data dir, for example: devdata") 18 | 19 | func main() { 20 | flag.Parse() 21 | db, err := chain_block.NewBlockDB(*dir) 22 | helper.AssertNil(err) 23 | location := &chain_file_manager.Location{ 24 | FileId: *fieldId, 25 | Offset: *offset, 26 | } 27 | sb, ab, next, err := db.ReadUnit(location) 28 | helper.AssertNil(err) 29 | fmt.Println("next location", next.FileId, next.Offset) 30 | if ab != nil { 31 | fmt.Println("account block", ab.AccountAddress, ab.Height, ab.Hash) 32 | byt, _ := json.Marshal(ab) 33 | fmt.Println(string(byt)) 34 | } 35 | if sb != nil { 36 | fmt.Println("snapshot block", sb.Height, sb.Hash) 37 | byt, _ := json.Marshal(sb) 38 | fmt.Println(string(byt)) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ledger/pool/batch/example_test.go: -------------------------------------------------------------------------------- 1 | package batch_test 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/vitelabs/go-vite/v2/common" 8 | "github.com/vitelabs/go-vite/v2/common/types" 9 | "github.com/vitelabs/go-vite/v2/ledger/pool/batch" 10 | ) 11 | 12 | // ExampleBatchSnapshot_Batch 13 | func ExampleBatchSnapshot_Batch() { 14 | b := batch.NewBatch(snapshotExists, accountExists, 1, 100) 15 | 16 | addr := common.MockAddress(1) 17 | aItem := batch.NewMockSendBlcok(batch.NewGenesisBlock(&addr)) 18 | 19 | var accBlocks []batch.Item 20 | accBlocks = append(accBlocks, aItem) 21 | sItem := batch.NewMockSnapshotBlock(batch.NewGenesisBlock(nil), accBlocks) 22 | 23 | b.AddAItem(aItem, nil) 24 | b.AddSItem(sItem) 25 | 26 | err := b.Batch(execute, execute) 27 | if err != nil { 28 | fmt.Println(err.Error()) 29 | } 30 | } 31 | 32 | func execute(p batch.Batch, l batch.Level, bucket batch.Bucket, version uint64) error { 33 | fmt.Println("execute ", l.Snapshot(), p.Version(), l.Index(), len(bucket.Items()), version) 34 | return nil 35 | } 36 | 37 | func snapshotExists(hash types.Hash) error { 38 | return nil 39 | } 40 | func accountExists(hash types.Hash) error { 41 | return nil 42 | } 43 | 44 | func TestExample(t *testing.T) { 45 | ExampleBatchSnapshot_Batch() 46 | } 47 | -------------------------------------------------------------------------------- /ledger/chain/genesis/snapshot_block.go: -------------------------------------------------------------------------------- 1 | package chain_genesis 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/vitelabs/go-vite/v2/interfaces" 7 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 8 | ) 9 | 10 | func newGenesisSnapshotContent(accountBlocks []*interfaces.VmAccountBlock) ledger.SnapshotContent { 11 | sc := make(ledger.SnapshotContent, len(accountBlocks)) 12 | for _, vmBlock := range accountBlocks { 13 | accountBlock := vmBlock.AccountBlock 14 | if hashHeight, ok := sc[accountBlock.AccountAddress]; !ok || hashHeight.Height < accountBlock.Height { 15 | sc[accountBlock.AccountAddress] = &ledger.HashHeight{ 16 | Height: accountBlock.Height, 17 | Hash: accountBlock.Hash, 18 | } 19 | } 20 | } 21 | 22 | return sc 23 | } 24 | 25 | func NewGenesisSnapshotBlock(accountBlocks []*interfaces.VmAccountBlock) *ledger.SnapshotBlock { 26 | // 2019/05/21 12:00:00 UTC/GMT +8 27 | genesisTimestamp := time.Unix(1558411200, 0) 28 | 29 | genesisSnapshotBlock := &ledger.SnapshotBlock{ 30 | Height: 1, // height 31 | Timestamp: &genesisTimestamp, // timestamp 32 | SnapshotContent: newGenesisSnapshotContent(accountBlocks), 33 | } 34 | 35 | genesisSnapshotBlock.Hash = genesisSnapshotBlock.ComputeHash() 36 | 37 | return genesisSnapshotBlock 38 | } 39 | -------------------------------------------------------------------------------- /.github/workflows/nightly-build.yml: -------------------------------------------------------------------------------- 1 | name: gvite-nightly-build 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | branch: 7 | description: 'nightly build from' 8 | required: true 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | ref: '${{ github.event.inputs.branch }}' 17 | 18 | - name: Set up Go 19 | uses: actions/setup-go@v2 20 | with: 21 | go-version: 1.16 22 | 23 | - name: Test 24 | run: make test 25 | 26 | - name: Get Build Version 27 | id: version 28 | run: echo "::set-output name=version::$(date +%Y%m%d%H%M)" 29 | 30 | - name: Build 31 | run: echo "${{ steps.version.outputs.version }}" > version/buildversion ; make all 32 | 33 | - name: Release 34 | run: cd build/cmd/gvite ;ls | grep -v ".tar.gz" | while read line; do tar zcvf $line.tar.gz $line ; openssl dgst -sha256 $line.tar.gz >> release.sha256.log ;done ; cd ../../../ 35 | 36 | - uses: actions/upload-artifact@v2 37 | with: 38 | name: "nightly-${{ github.event.inputs.branch }}-${{ steps.version.outputs.version }}" 39 | path: | 40 | build/cmd/gvite/*.tar.gz 41 | build/cmd/gvite/release.sha256.log -------------------------------------------------------------------------------- /net/mock_receiver.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 The go-vite Authors 3 | * This file is part of the go-vite library. 4 | * 5 | * The go-vite library is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Lesser General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * The go-vite library is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Lesser General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Lesser General Public License 16 | * along with the go-vite library. If not, see . 17 | */ 18 | 19 | package net 20 | 21 | import ( 22 | "github.com/vitelabs/go-vite/v2/common/types" 23 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 24 | ) 25 | 26 | type mockReceiver struct { 27 | } 28 | 29 | func (mockReceiver) receiveAccountBlock(block *ledger.AccountBlock, source types.BlockSource) error { 30 | return nil 31 | } 32 | 33 | func (mockReceiver) receiveSnapshotBlock(block *ledger.SnapshotBlock, source types.BlockSource) error { 34 | return nil 35 | } 36 | -------------------------------------------------------------------------------- /ledger/chain/index/index_db_test.go: -------------------------------------------------------------------------------- 1 | package chain_index 2 | 3 | import ( 4 | "path" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/vitelabs/go-vite/v2/common" 9 | "github.com/vitelabs/go-vite/v2/common/types" 10 | ) 11 | 12 | func TestDumpFileLocation(t *testing.T) { 13 | chainDir := path.Join(common.HomeDir(), ".gvite/mockdata/ledger") 14 | db, err := NewIndexDB(chainDir) 15 | assert.NoError(t, err) 16 | step := uint64(75 * 10) 17 | from := types.GenesisHeight 18 | 19 | for i := from; ; i = i + step { 20 | location, err := db.GetSnapshotBlockLocation(i) 21 | assert.NoError(t, err) 22 | if location == nil { 23 | break 24 | } 25 | t.Log(location.FileId, location.Offset) 26 | } 27 | } 28 | 29 | func TestIndexDB_GetLatestAccountBlock(t *testing.T) { 30 | t.Skip("Skipped by default. This test can be used to inspect IndexDB.") 31 | 32 | chainDir := path.Join(common.HomeDir(), ".gvite/mockdata/ledger") 33 | db, err := NewIndexDB(chainDir) 34 | assert.NoError(t, err) 35 | address, err := types.HexToAddress("vite_7c8c9e1e878e8a6ddf59c66a83791a5755a8fcf606c4bd31ea") 36 | assert.NoError(t, err) 37 | height, location, err := db.GetLatestAccountBlock(&address) 38 | assert.NoError(t, err) 39 | assert.NotNil(t, location) 40 | 41 | t.Log(height, location.FileId, location.Offset) 42 | } 43 | -------------------------------------------------------------------------------- /cmd/gvite_plugins/subcmd_demo.go: -------------------------------------------------------------------------------- 1 | package gvite_plugins 2 | 3 | import ( 4 | "fmt" 5 | 6 | "gopkg.in/urfave/cli.v1" 7 | 8 | "github.com/vitelabs/go-vite/v2/cmd/nodemanager" 9 | "github.com/vitelabs/go-vite/v2/cmd/utils" 10 | ) 11 | 12 | var ( 13 | demoFlags = utils.MergeFlags(utils.ConfigFlags, utils.GeneralFlags) 14 | 15 | //demo,please add this `demoCommand` to main.go 16 | /** 17 | app.Commands = []cli.Command{ 18 | versionCommand, 19 | licenseCommand, 20 | consoleCommand, 21 | attachCommand, 22 | demoCommand, 23 | } 24 | */ 25 | demoCommand = cli.Command{ 26 | Action: utils.MigrateFlags(demoAction), 27 | Name: "demo", 28 | Usage: "demo", 29 | Flags: demoFlags, 30 | Category: "DEMO COMMANDS", 31 | Description: `demo`, 32 | } 33 | ) 34 | 35 | // localConsole starts chain new gvite node, attaching chain JavaScript console to it at the same time. 36 | func demoAction(ctx *cli.Context) error { 37 | 38 | // Create and start the node based on the CLI flags 39 | nodeManager, err := nodemanager.NewSubCmdNodeManager(ctx, nodemanager.FullNodeMaker{}) 40 | if err != nil { 41 | fmt.Println("demo error", err) 42 | return err 43 | } 44 | nodeManager.Start() 45 | defer nodeManager.Stop() 46 | 47 | //Tips: add your code here 48 | fmt.Println("demo print") 49 | return nil 50 | } 51 | -------------------------------------------------------------------------------- /cmd/nodemanager/assist.go: -------------------------------------------------------------------------------- 1 | package nodemanager 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/vitelabs/go-vite/v2/common" 7 | "github.com/vitelabs/go-vite/v2/log15" 8 | "github.com/vitelabs/go-vite/v2/node" 9 | ) 10 | 11 | var ( 12 | log = log15.New("module", "gvite/node_manager") 13 | ) 14 | 15 | // start node 16 | func StartNode(node *node.Node) error { 17 | // Prepare the node 18 | log.Info(fmt.Sprintf("Starting prepare node...")) 19 | if err := node.Prepare(); err != nil { 20 | log.Error(fmt.Sprintf("Failed to prepare node, %v", err)) 21 | fmt.Println(fmt.Sprintf("Failed to prepare node, %v", err)) 22 | return err 23 | } 24 | 25 | // Start the node 26 | log.Info(fmt.Sprintf("Starting Node...")) 27 | if err := node.Start(); err != nil { 28 | fmt.Println(fmt.Sprintf("Failed to start node, %v", err)) 29 | common.Crit(fmt.Sprintf("Failed to start node, %v", err)) 30 | } 31 | 32 | node.Wait() 33 | return nil 34 | } 35 | 36 | // wait the node to stop 37 | func WaitNode(node *node.Node) { 38 | node.Wait() 39 | } 40 | 41 | // stop the node 42 | func StopNode(node *node.Node) { 43 | log.Warn("Stopping node...") 44 | 45 | //Stop the node Extenders 46 | log.Warn("Stopping node extenders...") 47 | 48 | if err := node.Stop(); err != nil { 49 | log.Error(fmt.Sprintf("Failed to stop node, %v", err)) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ledger/chain/account.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 8 | ) 9 | 10 | func (c *chain) GetAccountId(address types.Address) (uint64, error) { 11 | accountId, err := c.indexDB.GetAccountId(&address) 12 | 13 | if err != nil { 14 | cErr := fmt.Errorf("c.indexDB.GetAccountId failed, error is %s, address is %s", err.Error(), address) 15 | c.log.Error(cErr.Error(), "method", "GetAccountId") 16 | return 0, cErr 17 | } 18 | 19 | return accountId, nil 20 | } 21 | 22 | func (c *chain) GetAccountAddress(accountId uint64) (*types.Address, error) { 23 | addr, err := c.indexDB.GetAccountAddress(accountId) 24 | 25 | if err != nil { 26 | cErr := fmt.Errorf("c.indexDB.GetAccountAddress failed, error is %s, accountId is %d", err.Error(), accountId) 27 | c.log.Error(cErr.Error(), "method", "getAccountAddress") 28 | return nil, cErr 29 | } 30 | 31 | return addr, nil 32 | } 33 | 34 | func (c *chain) IterateAccounts(iterateFunc func(addr types.Address, accountId uint64, err error) bool) { 35 | c.indexDB.IterateAccounts(iterateFunc) 36 | } 37 | 38 | func (c *chain) IterateContracts(iterateFunc func(addr types.Address, meta *ledger.ContractMeta, err error) bool) { 39 | c.stateDB.IterateContracts(iterateFunc) 40 | } 41 | -------------------------------------------------------------------------------- /ledger/onroad/pending_cache_test.go: -------------------------------------------------------------------------------- 1 | package onroad 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | "math/rand" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | type tMap map[string][]*big.Int 12 | 13 | func (m tMap) Add(key string, value *big.Int) { 14 | if l, ok := m[key]; ok && l != nil { 15 | p := m[key] 16 | p = append(p, value) 17 | if &p != &l { 18 | fmt.Printf("copy, not pointer") 19 | } 20 | } else { 21 | newL := make([]*big.Int, 0) 22 | newL = append(newL, value) 23 | m[key] = newL 24 | } 25 | } 26 | 27 | func TestPendingCache_Map(t *testing.T) { 28 | tmap := make(tMap) 29 | strList := []string{"a", "b", "c", "d"} 30 | 31 | rand.Seed(time.Now().UnixNano()) 32 | for i := 0; i < len(strList)-1; i++ { 33 | l := make([]*big.Int, 0) 34 | for j := 0; j < 2; j++ { 35 | l = append(l, big.NewInt(int64(i))) 36 | } 37 | tmap[strList[rand.Intn(len(strList))]] = l 38 | } 39 | 40 | for k, l := range tmap { 41 | for _, v := range l { 42 | fmt.Printf("tMap[%v]=%v\t", k, v) 43 | } 44 | } 45 | 46 | addKey := strList[rand.Intn(len(strList))] 47 | fmt.Printf("befor %v\n", len(tmap[addKey])) 48 | tmap.Add(addKey, big.NewInt(9)) 49 | fmt.Printf("after %v\n", len(tmap[addKey])) 50 | if _, ok := tmap[addKey]; ok { 51 | for _, v := range tmap[addKey] { 52 | fmt.Printf("%v \t", v) 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /rpc/inproc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The go-ethereum Authors 2 | // This file is part of the go-ethereum library. 3 | // 4 | // The go-ethereum library is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU Lesser General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // The go-ethereum library is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU Lesser General Public License for more details. 13 | // 14 | // You should have received chain copy of the GNU Lesser General Public License 15 | // along with the go-ethereum library. If not, see . 16 | 17 | package rpc 18 | 19 | import ( 20 | "context" 21 | "net" 22 | ) 23 | 24 | // DialInProc attaches an in-process connection to the given RPC server. 25 | func DialInProc(handler *Server) *Client { 26 | initctx := context.Background() 27 | c, _ := newClient(initctx, func(context.Context) (net.Conn, error) { 28 | p1, p2 := net.Pipe() 29 | go handler.ServeCodec(NewJSONCodec(p1), OptionMethodInvocation|OptionSubscriptions) 30 | return p2, nil 31 | }) 32 | return c 33 | } 34 | -------------------------------------------------------------------------------- /ledger/chain/cache/hot_data.go: -------------------------------------------------------------------------------- 1 | package chain_cache 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/types" 5 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 6 | ) 7 | 8 | type hotData struct { 9 | ds *dataSet 10 | 11 | latestSnapshotBlock *ledger.SnapshotBlock 12 | 13 | latestAccountBlocks map[types.Address]types.Hash 14 | } 15 | 16 | func newHotData(ds *dataSet) *hotData { 17 | return &hotData{ 18 | ds: ds, 19 | latestAccountBlocks: make(map[types.Address]types.Hash), 20 | } 21 | } 22 | 23 | func (hd *hotData) SetLatestSnapshotBlock(snapshotBlock *ledger.SnapshotBlock) { 24 | hd.latestSnapshotBlock = snapshotBlock 25 | } 26 | 27 | func (hd *hotData) GetLatestSnapshotBlock() *ledger.SnapshotBlock { 28 | return hd.latestSnapshotBlock 29 | } 30 | 31 | func (hd *hotData) InsertAccountBlock(block *ledger.AccountBlock) { 32 | hd.latestAccountBlocks[block.AccountAddress] = block.Hash 33 | } 34 | 35 | func (hd *hotData) DeleteAccountBlocks(blocks []*ledger.AccountBlock) { 36 | for _, block := range blocks { 37 | delete(hd.latestAccountBlocks, block.AccountAddress) 38 | } 39 | } 40 | 41 | func (hd *hotData) GetLatestAccountBlock(addr types.Address) *ledger.AccountBlock { 42 | hash, ok := hd.latestAccountBlocks[addr] 43 | if !ok { 44 | return nil 45 | } 46 | 47 | return hd.ds.GetAccountBlock(hash) 48 | } 49 | -------------------------------------------------------------------------------- /ledger/chain/db/rollback.go: -------------------------------------------------------------------------------- 1 | package chain_db 2 | 3 | import ( 4 | "github.com/vitelabs/go-vite/v2/common/db/xleveldb" 5 | "github.com/vitelabs/go-vite/v2/common/types" 6 | ledger "github.com/vitelabs/go-vite/v2/interfaces/core" 7 | ) 8 | 9 | // rollback 10 | func (store *Store) RollbackAccountBlocks(rollbackBatch *leveldb.Batch, accountBlocks []*ledger.AccountBlock) { 11 | // delete store.unconfirmedBatchMap 12 | for _, block := range accountBlocks { 13 | store.unconfirmedBatchs.Remove(block.Hash) 14 | } 15 | 16 | // write store.memDb 17 | store.putMemDb(rollbackBatch) 18 | } 19 | 20 | // rollback 21 | func (store *Store) RollbackAccountBlockByHash(rollbackBatch *leveldb.Batch, blockHashList []types.Hash) { 22 | // delete store.unconfirmedBatchMap 23 | for _, blockHash := range blockHashList { 24 | // remove 25 | store.unconfirmedBatchs.Remove(blockHash) 26 | } 27 | 28 | // write store.memDb 29 | store.putMemDb(rollbackBatch) 30 | } 31 | 32 | func (store *Store) RollbackSnapshot(rollbackBatch *leveldb.Batch) { 33 | // write store.memDb 34 | store.putMemDb(rollbackBatch) 35 | 36 | // set store.snapshotBatch 37 | store.unconfirmedBatchs.All(func(batch *leveldb.Batch) { 38 | store.snapshotBatch.Append(batch) 39 | }) 40 | 41 | store.snapshotBatch.Append(rollbackBatch) 42 | 43 | // reset 44 | store.unconfirmedBatchs.Clear() 45 | } 46 | -------------------------------------------------------------------------------- /common/db/xleveldb/comparer/bytes_comparer.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, Suryandaru Triandana 2 | // All rights reserved. 3 | // 4 | // Use of this source code is governed by a BSD-style license that can be 5 | // found in the LICENSE file. 6 | 7 | package comparer 8 | 9 | import "bytes" 10 | 11 | type bytesComparer struct{} 12 | 13 | func (bytesComparer) Compare(a, b []byte) int { 14 | return bytes.Compare(a, b) 15 | } 16 | 17 | func (bytesComparer) Name() string { 18 | return "leveldb.BytewiseComparator" 19 | } 20 | 21 | func (bytesComparer) Separator(dst, a, b []byte) []byte { 22 | i, n := 0, len(a) 23 | if n > len(b) { 24 | n = len(b) 25 | } 26 | for ; i < n && a[i] == b[i]; i++ { 27 | } 28 | if i >= n { 29 | // Do not shorten if one string is a prefix of the other 30 | } else if c := a[i]; c < 0xff && c+1 < b[i] { 31 | dst = append(dst, a[:i+1]...) 32 | dst[i]++ 33 | return dst 34 | } 35 | return nil 36 | } 37 | 38 | func (bytesComparer) Successor(dst, b []byte) []byte { 39 | for i, c := range b { 40 | if c != 0xff { 41 | dst = append(dst, b[:i+1]...) 42 | dst[i]++ 43 | return dst 44 | } 45 | } 46 | return nil 47 | } 48 | 49 | // DefaultComparer are default implementation of the Comparer interface. 50 | // It uses the natural ordering, consistent with bytes.Compare. 51 | var DefaultComparer = bytesComparer{} 52 | -------------------------------------------------------------------------------- /cmd/nodemanager/export_node_manager.go: -------------------------------------------------------------------------------- 1 | package nodemanager 2 | 3 | import ( 4 | "math/big" 5 | 6 | "gopkg.in/urfave/cli.v1" 7 | 8 | "github.com/vitelabs/go-vite/v2/cmd/utils" 9 | "github.com/vitelabs/go-vite/v2/node" 10 | ) 11 | 12 | type ExportNodeManager struct { 13 | ctx *cli.Context 14 | node *node.Node 15 | } 16 | 17 | var digits = big.NewInt(1000000000000000000) 18 | 19 | func NewExportNodeManager(ctx *cli.Context, maker NodeMaker) (*ExportNodeManager, error) { 20 | node, err := maker.MakeNode(ctx) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | // single mode 26 | node.Config().Single = true 27 | node.ViteConfig().Net.Single = true 28 | 29 | // no miner 30 | node.Config().MinerEnabled = false 31 | node.ViteConfig().Producer.Producer = false 32 | 33 | // no ledger gc 34 | ledgerGc := false 35 | node.Config().LedgerGc = &ledgerGc 36 | node.ViteConfig().Chain.LedgerGc = ledgerGc 37 | 38 | return &ExportNodeManager{ 39 | ctx: ctx, 40 | node: node, 41 | }, nil 42 | } 43 | 44 | func (nodeManager *ExportNodeManager) getSbHeight() uint64 { 45 | sbHeight := uint64(0) 46 | if nodeManager.ctx.GlobalIsSet(utils.ExportSbHeightFlags.Name) { 47 | sbHeight = nodeManager.ctx.GlobalUint64(utils.ExportSbHeightFlags.Name) 48 | } 49 | return sbHeight 50 | } 51 | 52 | func (nodeManager *ExportNodeManager) Start() error { 53 | 54 | return nil 55 | 56 | } 57 | -------------------------------------------------------------------------------- /tools/circle/list.go: -------------------------------------------------------------------------------- 1 | package circle 2 | 3 | type List interface { 4 | Size() int 5 | Put(key Key) (old Key) 6 | Traverse(func(key Key) bool) // from low to high 7 | TraverseR(func(key Key) bool) // from high to low 8 | Reset() 9 | } 10 | 11 | type list struct { 12 | front int 13 | rear int 14 | total int 15 | l []Key // has chain zero slot 16 | } 17 | 18 | func (l *list) Reset() { 19 | l.front = 0 20 | l.rear = 0 21 | } 22 | 23 | func (l *list) Traverse(fn func(key Key) bool) { 24 | for i := l.front; i != l.rear; i = (i + 1) % l.total { 25 | if !fn(l.l[i]) { 26 | break 27 | } 28 | } 29 | } 30 | 31 | func (l *list) TraverseR(fn func(key Key) bool) { 32 | var index int 33 | for i := l.rear; i != l.front; i = index { 34 | index = (i - 1 + l.total) % l.total 35 | if !fn(l.l[index]) { 36 | break 37 | } 38 | } 39 | } 40 | 41 | func (l *list) Size() int { 42 | return (l.rear - l.front + l.total) % l.total 43 | } 44 | 45 | func (l *list) Put(key Key) (replaced Key) { 46 | // list is full 47 | if (l.rear+1)%l.total == l.front { 48 | replaced = l.l[l.front] 49 | l.front = (l.front + 1) % l.total 50 | } 51 | 52 | l.l[l.rear] = key 53 | l.rear = (l.rear + 1) % l.total 54 | 55 | return 56 | } 57 | 58 | func NewList(total int) List { 59 | return &list{ 60 | front: 0, 61 | rear: 0, 62 | total: total + 1, 63 | l: make([]Key, total+1), 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /wallet/wallet.go: -------------------------------------------------------------------------------- 1 | package wallet 2 | 3 | import ( 4 | "github.com/tyler-smith/go-bip39" 5 | 6 | "github.com/vitelabs/go-vite/v2/common/types" 7 | "github.com/vitelabs/go-vite/v2/crypto/ed25519" 8 | "github.com/vitelabs/go-vite/v2/wallet/hd-bip/derivation" 9 | ) 10 | 11 | func RandomMnemonic24() (types.Address, ed25519.PrivateKey, string, error) { 12 | entropy, err := bip39.NewEntropy(256) 13 | if err != nil { 14 | return types.Address{}, nil, "", err 15 | } 16 | return newMnemonic(entropy) 17 | } 18 | 19 | func RandomMnemonic12() (types.Address, ed25519.PrivateKey, string, error) { 20 | entropy, err := bip39.NewEntropy(128) 21 | if err != nil { 22 | return types.Address{}, nil, "", err 23 | } 24 | return newMnemonic(entropy) 25 | } 26 | 27 | func newMnemonic(entropy []byte) (types.Address, ed25519.PrivateKey, string, error) { 28 | mnemonic, err := bip39.NewMnemonic(entropy) 29 | if err != nil { 30 | return types.Address{}, nil, "", err 31 | } 32 | seed := bip39.NewSeed(mnemonic, "") 33 | key, err := derivation.DeriveWithIndex(0, seed) 34 | if err != nil { 35 | return types.Address{}, nil, "", err 36 | } 37 | address, err := key.Address() 38 | if err != nil { 39 | return types.Address{}, nil, "", err 40 | } 41 | priKeys, err := key.PrivateKey() 42 | if err != nil { 43 | return types.Address{}, nil, "", err 44 | } 45 | return *address, priKeys, mnemonic, nil 46 | } 47 | -------------------------------------------------------------------------------- /ledger/chain/sync_cache/cache_item_test.go: -------------------------------------------------------------------------------- 1 | package sync_cache 2 | 3 | import ( 4 | "crypto/rand" 5 | "testing" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/types" 8 | "github.com/vitelabs/go-vite/v2/interfaces" 9 | ) 10 | 11 | func TestCacheItem_Serialize(t *testing.T) { 12 | var c = cacheItem{ 13 | Segment: interfaces.Segment{ 14 | From: 101, 15 | To: 1000, 16 | Hash: types.Hash{}, 17 | PrevHash: types.Hash{}, 18 | Points: nil, 19 | }, 20 | done: true, 21 | verified: true, 22 | filename: "chunk101_1000", 23 | size: 1837, 24 | } 25 | 26 | rand.Read(c.Hash[:]) 27 | rand.Read(c.PrevHash[:]) 28 | 29 | data, err := c.Serialize() 30 | if err != nil { 31 | panic(err) 32 | } 33 | 34 | var c2 = &cacheItem{} 35 | err = c2.DeSerialize(data) 36 | if err != nil { 37 | panic(err) 38 | } 39 | 40 | if false == c.Segment.Equal(c2.Segment) { 41 | t.Errorf("different segment") 42 | } 43 | for i, p := range c.Points { 44 | if c2.Points[i].Height != p.Height || c2.Points[i].Hash != p.Hash { 45 | t.Errorf("different point") 46 | } 47 | } 48 | if c.verified != c2.verified { 49 | t.Error("different verified") 50 | } 51 | if c.filename != c2.filename { 52 | t.Error("different filename") 53 | } 54 | if c.done != c2.done { 55 | t.Errorf("different done") 56 | } 57 | if c.size != c2.size { 58 | t.Errorf("different size") 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /ledger/pipeline/blocks_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/vitelabs/go-vite/v2/common/fileutils" 8 | "github.com/vitelabs/go-vite/v2/interfaces/core" 9 | chain_block "github.com/vitelabs/go-vite/v2/ledger/chain/block" 10 | ) 11 | 12 | func prepareTestData(t *testing.T, dir string) { 13 | // prepare once 14 | if _, err := os.Stat(dir + "/lock"); os.IsNotExist(err) { 15 | // os.RemoveAll(dir) 16 | os.Create(dir + "/lock") 17 | } else { 18 | return 19 | } 20 | 21 | blockDb, err := chain_block.NewBlockDBFixedSize(dir, testFilesize) 22 | if err != nil { 23 | t.Error(err) 24 | t.FailNow() 25 | } 26 | defer blockDb.Close() 27 | 28 | len := 3000 29 | for i := 0; i < len; i++ { 30 | var block core.SnapshotBlock 31 | block.Mock(uint64(i)) 32 | 33 | chunk := &core.SnapshotChunk{} 34 | chunk.SnapshotBlock = &block 35 | _, _, err = blockDb.Write(chunk) 36 | if err != nil { 37 | t.Error(err) 38 | t.FailNow() 39 | } 40 | } 41 | 42 | blockDb.Prepare() 43 | blockDb.Commit() 44 | 45 | t.Log("prepare data done", dir) 46 | } 47 | 48 | var ( 49 | tmpDir = fileutils.CreateTempDir() 50 | testFilesize = int64(5 * 1024) 51 | ) 52 | 53 | func TestNewBlocks(t *testing.T) { 54 | prepareTestData(t, tmpDir) 55 | _, err := newBlocks(tmpDir, testFilesize) 56 | if err != nil { 57 | t.Error(err) 58 | t.FailNow() 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /client/abi_client_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "encoding/base64" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | 10 | "github.com/vitelabs/go-vite/v2/common/types" 11 | "github.com/vitelabs/go-vite/v2/vm/abi" 12 | ) 13 | 14 | func TestAbiCli_CallOffChain(t *testing.T) { 15 | t.Skip("Skipped by default. This test can be used to call off-chain contract methods.") 16 | 17 | rpc := PreTestRpc(t, RawUrl) 18 | 19 | abi := `` 20 | offchainCode := `` 21 | contract := types.HexToAddressPanic("") 22 | 23 | abiCli, err := GetAbiCli(rpc, abi, offchainCode, contract) 24 | if err != nil { 25 | t.Fatal(err) 26 | } 27 | 28 | result, err := abiCli.CallOffChain("") 29 | if err != nil { 30 | t.Fatal(err) 31 | } 32 | for k, v := range result { 33 | t.Log(k, v) 34 | } 35 | } 36 | 37 | func TestUnpack(t *testing.T) { 38 | t.Skip("Skipped by default. This test can be used to unpack contract methods.") 39 | 40 | abiCode := `` 41 | contract, err := abi.JSONToABIContract(strings.NewReader(abiCode)) 42 | assert.NoError(t, err) 43 | 44 | data, err := base64.StdEncoding.DecodeString("") 45 | assert.NoError(t, err) 46 | 47 | id, err := contract.MethodById(data[0:4]) 48 | assert.NoError(t, err) 49 | t.Log(id) 50 | var inputs types.Address 51 | 52 | err = contract.UnpackMethod(&inputs, id.Name, data) 53 | assert.NoError(t, err) 54 | 55 | t.Log(inputs) 56 | } 57 | --------------------------------------------------------------------------------