ngtypes

package
Version: v0.0.0-...-8d08d5c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 26, 2021 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package ngtypes implements the block structure and related types.

# RULE: NGTYPES

## Account

Account is not an unlimited resource, the account is created when register tx and removed with logout tx

## Block

Block is not only a tx mass, but a vault for network status.

It means that the security can be ensured with a specific length sub-chain, the blocks before the chain can be throw.

The block has several steps to be mature

(sheetHash)--> BareBlock --(+txs&mtree)--> Unsealing --(+nonce)--> SealedBlock

The sheetHash is the sheet before applying block txs.

## Tx

Tx is a basic operation method in NGIN network, acting as extendable structure for the network's functions.

Tx can handle more than one transfer of coins or operations because of it's values field and participants field. Also, with the schnorr signature, the coin can be owned by multi-person at the same time and the account is able to send tx only when all owners signed the tx.

Currently, there are 5 types of tx

1. Generate Tx: generate tx works when generating the coin, only miner can send this, and it can also have multi-participants.

2. Register Tx: register the account

3. Logout Tx: logout the account

4. Transaction: normal tx, can be used for sending money, or trigger the vm's onTx function

5. Assign Tx: assign raw bytes to Contract, overwriting

5. Append Tx: append raw bytes to Contract

## Sheet

Sheet is the aggregation of all status, not only accounts, but anonymous addresses

Index

Constants

View Source
const (
	TargetTime      = 16 * time.Second // change time from 10 -> 16 = 1 << 4
	BlockCheckRound = 10               // do fork if fall behind one round
)

PoW const

View Source
const (
	// !NO MAX LIMITATION!
	//BlockMaxTxsSize = 1 << 25 // 32M
	TxMaxExtraSize = 1 << 20 // if more than 1m, extra should be separated ot multi append
	// The length of a timestemp bytes
	TimestampSize = 8
	// The length of a hash bytes
	HashSize = 32
	// The length of a nonce bytes
	NonceSize = 8 // nonce uses 8 bytes

	// some for tx
	AddressSize   = 35
	SignatureSize = 64 // signature uses 64 bytes, R 32 & S 32
)

Maximum sizes

View Source
const (
	FloatNG = 1_000_000_000_000_000_000.0
)

Unit const

View Source
const (
	GenesisAddressBase58 = "QVSdpMLFwUtECb3SxgLt8YeQwkHGmzh5ZexjGCUB2E5koFhJ"
)

FIXME: before initializing new network, should manually init PK & Sign use `go run ./cmd/ngcore gentools check` check and generate valid values

Variables

decoded genesis variables

View Source
var (
	NG       = new(big.Int).SetUint64(pico)
	NGSymbol = "NG"
)

Units variables: https://en.wikipedia.org/wiki/Unit_prefix https://en.wikipedia.org/wiki/Metric_prefix

View Source
var (
	NetworkType_name = map[int32]string{
		0: "ZERONET",
		1: "TESTNET",
		2: "MAINNET",
	}
	NetworkType_value = map[string]int32{
		"ZERONET": 0,
		"TESTNET": 1,
		"MAINNET": 2,
	}
)

Enum value maps for NetworkType.

View Source
var (
	TxType_name = map[int32]string{
		0:  "INVALID",
		1:  "GENERATE",
		2:  "REGISTER",
		3:  "LOGOUT",
		10: "TRANSACTION",
		20: "ASSIGN",
		21: "APPEND",
	}
	TxType_value = map[string]int32{
		"INVALID":     0,
		"GENERATE":    1,
		"REGISTER":    2,
		"LOGOUT":      3,
		"TRANSACTION": 10,
		"ASSIGN":      20,
		"APPEND":      21,
	}
)

Enum value maps for TxType.

View Source
var (
	ErrTxWrongSign = errors.New("the signer of transaction is not the own of the account")
)

Errors for Tx

View Source
var File_types_proto protoreflect.FileDescriptor
View Source
var GenesisBalances map[string][]byte
View Source
var (

	// Max Value of Target
	MaxTarget = new(big.Int).SetBytes([]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
		255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255})
)

PoW variables

View Source
var RegisterFee = new(big.Int).Mul(NG, big.NewInt(registerFeeNG))

Functions

func BigIntsToBytesList

func BigIntsToBytesList(bigInts []*big.Int) [][]byte

BigIntsToBytesList is a helper converts bigInts to raw bytes slice.

func GetBlockReward

func GetBlockReward(height uint64) *big.Int

reward = 2 + 8*(0.9)^Era

func GetEmptyHash

func GetEmptyHash() []byte

GetEmptyHash return an empty hash

func GetGenesisBlockHash

func GetGenesisBlockHash(network NetworkType) []byte

func GetGenesisBlockNonce

func GetGenesisBlockNonce(network NetworkType) []byte

func GetGenesisGenerateTxSignature

func GetGenesisGenerateTxSignature(network NetworkType) []byte

func GetGenesisTimestamp

func GetGenesisTimestamp(network NetworkType) int64

GenesisTimestamp must be the time chain started, or the difficulty algo wont work FIXME: should be the time network starts

func GetNextDiff

func GetNextDiff(blockHeight uint64, blockTime int64, tailBlock *Block) *big.Int

GetNextDiff is a helper to get next pow block Diff field.

func TxsToMerkleTreeContents

func TxsToMerkleTreeContents(txs []*Tx) []merkletree.Content

TxsToMerkleTreeContents make a []merkletree.Content whose values is from txs.

Types

type Account

type Account struct {
	Num      uint64 `protobuf:"varint,1,opt,name=num,proto3" json:"num,omitempty"`
	Owner    []byte `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"`       // address -> balance in anonymous fields
	Contract []byte `protobuf:"bytes,5,opt,name=contract,proto3" json:"contract,omitempty"` // separate the code and state
	Context  []byte `protobuf:"bytes,6,opt,name=context,proto3" json:"context,omitempty"`
	// contains filtered or unexported fields
}

func GetGenesisStyleAccount

func GetGenesisStyleAccount(num AccountNum) *Account

GetGenesisStyleAccount will return the genesis style account.

func NewAccount

func NewAccount(num AccountNum, ownerAddress, contract, context []byte) *Account

NewAccount receive parameters and return a new Account(class constructor.

func (*Account) Descriptor deprecated

func (*Account) Descriptor() ([]byte, []int)

Deprecated: Use Account.ProtoReflect.Descriptor instead.

func (*Account) GetContext

func (x *Account) GetContext() []byte

func (*Account) GetContract

func (x *Account) GetContract() []byte

func (*Account) GetNum

func (x *Account) GetNum() uint64

func (*Account) GetOwner

func (x *Account) GetOwner() []byte

func (*Account) MarshalJSON

func (x *Account) MarshalJSON() ([]byte, error)

func (*Account) ProtoMessage

func (*Account) ProtoMessage()

func (*Account) ProtoReflect

func (x *Account) ProtoReflect() protoreflect.Message

func (*Account) Reset

func (x *Account) Reset()

func (*Account) String

func (x *Account) String() string

func (*Account) UnmarshalJSON

func (x *Account) UnmarshalJSON(data []byte) error

type AccountNum

type AccountNum uint64

func NewNumFromBytes

func NewNumFromBytes(b []byte) AccountNum

func (AccountNum) Bytes

func (num AccountNum) Bytes() []byte

type Address

type Address []byte

Address is the anonymous address for receiving coin, 2+33=35 length

func NewAddress

func NewAddress(privKey *secp256k1.PrivateKey) Address

NewAddress will return a 2+33=35 bytes length address

func NewAddressFromBS58

func NewAddressFromBS58(s string) (Address, error)

func NewAddressFromMultiKeys

func NewAddressFromMultiKeys(privKeys ...*secp256k1.PrivateKey) (Address, error)

NewAddressFromMultiKeys will return a 2+33=35 bytes length address

func (Address) BS58

func (a Address) BS58() string

func (Address) MarshalJSON

func (a Address) MarshalJSON() ([]byte, error)

func (Address) PubKey

func (a Address) PubKey() secp256k1.PublicKey

PubKey gets the public key from address for validition

func (Address) String

func (a Address) String() string

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(b []byte) error

type Block

type Block struct {
	Network       NetworkType `protobuf:"varint,1,opt,name=network,proto3,enum=ngtypes.NetworkType" json:"network,omitempty"`
	Height        uint64      `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"`
	Timestamp     int64       `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
	PrevBlockHash []byte      `protobuf:"bytes,4,opt,name=prev_block_hash,json=prevBlockHash,proto3" json:"prev_block_hash,omitempty"`
	TrieHash      []byte      `protobuf:"bytes,5,opt,name=trie_hash,json=trieHash,proto3" json:"trie_hash,omitempty"`
	Difficulty    []byte      `protobuf:"bytes,7,opt,name=difficulty,proto3" json:"difficulty,omitempty"` // diff = maxTarget / Big(header_hash)
	Nonce         []byte      `protobuf:"bytes,8,opt,name=nonce,proto3" json:"nonce,omitempty"`
	Txs           []*Tx       `protobuf:"bytes,10,rep,name=txs,proto3" json:"txs,omitempty"` // miner should build the generate tx by themselves
	// contains filtered or unexported fields
}

func GetGenesisBlock

func GetGenesisBlock(network NetworkType) *Block

GetGenesisBlock will return a complete sealed GenesisBlock.

func NewBareBlock

func NewBareBlock(network NetworkType, height uint64, blockTime int64, prevBlockHash []byte, diff *big.Int) *Block

NewBareBlock will return an unsealing block and then you need to add txs and seal with the correct N.

func (*Block) ApplyPoWRawAndTxs

func (x *Block) ApplyPoWRawAndTxs(raw []byte, txs []*Tx) error

ApplyPoWRawAndTxs will apply the raw pow of header and txs to the block.

func (*Block) CheckError

func (x *Block) CheckError() error

CheckError will check the errors in block inner fields.

func (*Block) Descriptor deprecated

func (*Block) Descriptor() ([]byte, []int)

Deprecated: Use Block.ProtoReflect.Descriptor instead.

func (*Block) GetActualDiff

func (x *Block) GetActualDiff() *big.Int

GetActualDiff returns the diff decided by nonce.

func (*Block) GetDifficulty

func (x *Block) GetDifficulty() []byte

func (*Block) GetHeight

func (x *Block) GetHeight() uint64

func (*Block) GetNetwork

func (x *Block) GetNetwork() NetworkType

func (*Block) GetNonce

func (x *Block) GetNonce() []byte

func (*Block) GetPoWRawHeader

func (x *Block) GetPoWRawHeader(nonce []byte) []byte

GetPoWRawHeader will return a complete raw for block hash. When nonce is not nil, the RawHeader will use the nonce param not the x.Nonce.

func (*Block) GetPrevBlockHash

func (x *Block) GetPrevBlockHash() []byte

func (*Block) GetPrevHash

func (x *Block) GetPrevHash() []byte

GetPrevHash is a helper to get the prev block hash from block header.

func (*Block) GetTimestamp

func (x *Block) GetTimestamp() int64

func (*Block) GetTrieHash

func (x *Block) GetTrieHash() []byte

func (*Block) GetTxs

func (x *Block) GetTxs() []*Tx

func (*Block) Hash

func (x *Block) Hash() []byte

Hash will help you get the hash of block.

func (*Block) IsGenesis

func (x *Block) IsGenesis() bool

IsGenesis will check whether the Block is the genesis block.

func (*Block) IsHead

func (x *Block) IsHead() bool

IsHead will check whether the Block is the head(checkpoint).

func (*Block) IsSealed

func (x *Block) IsSealed() bool

IsSealed checks whether the block is sealed.

func (*Block) IsTail

func (x *Block) IsTail() bool

IsTail will check whether the Block is the tail(the one before head).

func (*Block) IsUnsealing

func (x *Block) IsUnsealing() bool

IsUnsealing checks whether the block is unsealing.

func (*Block) MarshalJSON

func (x *Block) MarshalJSON() ([]byte, error)

func (*Block) PowHash

func (x *Block) PowHash() []byte

PowHash will help you get the pow hash of block.

func (*Block) ProtoMessage

func (*Block) ProtoMessage()

func (*Block) ProtoReflect

func (x *Block) ProtoReflect() protoreflect.Message

func (*Block) Reset

func (x *Block) Reset()

func (*Block) String

func (x *Block) String() string

func (*Block) ToSealed

func (x *Block) ToSealed(nonce []byte) (*Block, error)

ToSealed converts an unsealing block to a sealed block.

func (*Block) ToUnsealing

func (x *Block) ToUnsealing(txsWithGen []*Tx) (*Block, error)

ToUnsealing converts a bare block to an unsealing block.

func (*Block) UnmarshalJSON

func (x *Block) UnmarshalJSON(data []byte) error

type NetworkType

type NetworkType int32
const (
	NetworkType_ZERONET NetworkType = 0 // ZERONET acts as the regression testnet
	NetworkType_TESTNET NetworkType = 1 // TESTNET uses odd number
	NetworkType_MAINNET NetworkType = 2 // MAINNET uses even number
)

func (NetworkType) Descriptor

func (NetworkType) Enum

func (x NetworkType) Enum() *NetworkType

func (NetworkType) EnumDescriptor deprecated

func (NetworkType) EnumDescriptor() ([]byte, []int)

Deprecated: Use NetworkType.Descriptor instead.

func (NetworkType) Number

func (x NetworkType) Number() protoreflect.EnumNumber

func (NetworkType) String

func (x NetworkType) String() string

func (NetworkType) Type

type Sheet

type Sheet struct {
	PrevBlockHash []byte            `protobuf:"bytes,1,opt,name=prevBlockHash,proto3" json:"prevBlockHash,omitempty"` // use prevBlockHash to replace height to keep uniqueness
	Anonymous     map[string][]byte ``                                                                                // bs58_address(aka anonymous recipient) -> balance
	/* 159-byte string literal not displayed */
	Accounts map[uint64]*Account `` /* 158-byte string literal not displayed */
	// contains filtered or unexported fields
}

Sheet is a simplified States

var GenesisSheet *Sheet

func NewSheet

func NewSheet(prevBlockHash []byte, accounts map[uint64]*Account, anonymous map[string][]byte) *Sheet

NewSheet gets the rows from db and return the sheet for transport/saving.

func (*Sheet) Descriptor deprecated

func (*Sheet) Descriptor() ([]byte, []int)

Deprecated: Use Sheet.ProtoReflect.Descriptor instead.

func (*Sheet) GetAccounts

func (x *Sheet) GetAccounts() map[uint64]*Account

func (*Sheet) GetAnonymous

func (x *Sheet) GetAnonymous() map[string][]byte

func (*Sheet) GetPrevBlockHash

func (x *Sheet) GetPrevBlockHash() []byte

func (*Sheet) Hash

func (x *Sheet) Hash() []byte

Hash mainly for calculating the tire root of txs and sign tx.

func (*Sheet) ProtoMessage

func (*Sheet) ProtoMessage()

func (*Sheet) ProtoReflect

func (x *Sheet) ProtoReflect() protoreflect.Message

func (*Sheet) Reset

func (x *Sheet) Reset()

func (*Sheet) String

func (x *Sheet) String() string

type Tx

type Tx struct {
	Network       NetworkType `protobuf:"varint,1,opt,name=network,proto3,enum=ngtypes.NetworkType" json:"network,omitempty"`
	Type          TxType      `protobuf:"varint,2,opt,name=type,proto3,enum=ngtypes.TxType" json:"type,omitempty"`
	PrevBlockHash []byte      `protobuf:"bytes,3,opt,name=prev_block_hash,json=prevBlockHash,proto3" json:"prev_block_hash,omitempty"` // only available within one block
	Convener      uint64      `protobuf:"varint,4,opt,name=convener,proto3" json:"convener,omitempty"`                                 // account num required
	Participants  [][]byte    `protobuf:"bytes,5,rep,name=participants,proto3" json:"participants,omitempty"`
	Fee           []byte      `protobuf:"bytes,6,opt,name=fee,proto3" json:"fee,omitempty"`
	Values        [][]byte    `protobuf:"bytes,7,rep,name=values,proto3" json:"values,omitempty"`
	// extension
	Extra []byte `protobuf:"bytes,8,opt,name=extra,proto3" json:"extra,omitempty"`
	Sign  []byte `protobuf:"bytes,9,opt,name=sign,proto3" json:"sign,omitempty"`
	// contains filtered or unexported fields
}

Or you can call it Op

func GetGenesisGenerateTx

func GetGenesisGenerateTx(network NetworkType) *Tx

func NewUnsignedTx

func NewUnsignedTx(network NetworkType, txType TxType, prevBlockHash []byte, convener uint64, participants [][]byte, values []*big.Int, fee *big.Int, extraData []byte) *Tx

NewUnsignedTx will return an unsigned tx, must using Signature().

func (*Tx) BS58

func (x *Tx) BS58() string

BS58 is a tx's Readable Raw in string.

func (*Tx) CalculateHash

func (x *Tx) CalculateHash() ([]byte, error)

CalculateHash mainly for calculating the tire root of txs and sign tx.

func (*Tx) CheckAppend

func (x *Tx) CheckAppend(key secp256k1.PublicKey) error

CheckAppend does a self check for append tx

func (*Tx) CheckAssign

func (x *Tx) CheckAssign(publicKey secp256k1.PublicKey) error

CheckAssign does a self check for assign tx

func (*Tx) CheckGenerate

func (x *Tx) CheckGenerate(blockHeight uint64) error

CheckGenerate does a self check for generate tx

func (*Tx) CheckLogout

func (x *Tx) CheckLogout(publicKey secp256k1.PublicKey) error

CheckLogout does a self check for logout tx

func (*Tx) CheckRegister

func (x *Tx) CheckRegister() error

CheckRegister does a self check for register tx

func (*Tx) CheckTransaction

func (x *Tx) CheckTransaction(publicKey secp256k1.PublicKey) error

CheckTransaction does a self check for normal transaction tx

func (*Tx) Descriptor deprecated

func (*Tx) Descriptor() ([]byte, []int)

Deprecated: Use Tx.ProtoReflect.Descriptor instead.

func (*Tx) Equals

func (x *Tx) Equals(other merkletree.Content) (bool, error)

Equals mainly for calculating the tire root of txs.

func (*Tx) GetConvener

func (x *Tx) GetConvener() uint64

func (*Tx) GetExtra

func (x *Tx) GetExtra() []byte

func (*Tx) GetFee

func (x *Tx) GetFee() []byte

func (*Tx) GetNetwork

func (x *Tx) GetNetwork() NetworkType

func (*Tx) GetParticipants

func (x *Tx) GetParticipants() [][]byte

func (*Tx) GetPrevBlockHash

func (x *Tx) GetPrevBlockHash() []byte

func (*Tx) GetSign

func (x *Tx) GetSign() []byte

func (*Tx) GetType

func (x *Tx) GetType() TxType

func (*Tx) GetValues

func (x *Tx) GetValues() [][]byte

func (*Tx) Hash

func (x *Tx) Hash() []byte

Hash mainly for calculating the tire root of txs and sign tx.

func (*Tx) ID

func (x *Tx) ID() string

ID is a tx's Readable ID(hash) in string.

func (*Tx) IsSigned

func (x *Tx) IsSigned() bool

IsSigned will return whether the op has been signed.

func (*Tx) MarshalJSON

func (x *Tx) MarshalJSON() ([]byte, error)

func (*Tx) ProtoMessage

func (*Tx) ProtoMessage()

func (*Tx) ProtoReflect

func (x *Tx) ProtoReflect() protoreflect.Message

func (*Tx) Reset

func (x *Tx) Reset()

func (*Tx) Signature

func (x *Tx) Signature(privateKeys ...*secp256k1.PrivateKey) (err error)

Signature will re-sign the Tx with private key.

func (*Tx) String

func (x *Tx) String() string

func (*Tx) TotalExpenditure

func (x *Tx) TotalExpenditure() *big.Int

TotalExpenditure helps calculate the total expenditure which the tx caller should pay

func (*Tx) UnmarshalJSON

func (x *Tx) UnmarshalJSON(b []byte) error

func (*Tx) Verify

func (x *Tx) Verify(publicKey secp256k1.PublicKey) error

Verify helps verify the transaction whether signed by the public key owner.

type TxTrie

type TxTrie struct {
	Txs []*Tx
}

TxTrie is a fixed ordered tx container, mainly for pending. And TxTrie is an advanced type, aiming to get the trie root hash.

func NewTxTrie

func NewTxTrie(txs []*Tx) *TxTrie

NewTxTrie receives ordered ops.

func (*TxTrie) Append

func (tt *TxTrie) Append(tx *Tx)

Append will append new tx to the end of TxTrie's txs.

func (*TxTrie) Contains

func (tt *TxTrie) Contains(tx *Tx) bool

Contains determine if tt.Txs and tx are equal.

func (*TxTrie) Del

func (tt *TxTrie) Del(tx *Tx) error

Del removes a tx from txs.

func (*TxTrie) TrieRoot

func (tt *TxTrie) TrieRoot() []byte

TrieRoot sort tx tire by trie tree and return the root hash.

type TxType

type TxType int32
const (
	TxType_INVALID     TxType = 0
	TxType_GENERATE    TxType = 1
	TxType_REGISTER    TxType = 2
	TxType_LOGOUT      TxType = 3
	TxType_TRANSACTION TxType = 10
	TxType_ASSIGN      TxType = 20
	TxType_APPEND      TxType = 21
)

func (TxType) Descriptor

func (TxType) Descriptor() protoreflect.EnumDescriptor

func (TxType) Enum

func (x TxType) Enum() *TxType

func (TxType) EnumDescriptor deprecated

func (TxType) EnumDescriptor() ([]byte, []int)

Deprecated: Use TxType.Descriptor instead.

func (TxType) Number

func (x TxType) Number() protoreflect.EnumNumber

func (TxType) String

func (x TxType) String() string

func (TxType) Type

func (TxType) Type() protoreflect.EnumType

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL