ngtypes

package
v0.0.0-...-571fd38 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2021 License: GPL-3.0 Imports: 19 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 destroy 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 the ngchain 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. Destroy Tx: destroy 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
	BlockCheckRound = 10 // do converge if fall behind one round

	MatureRound  = 10                            // not mandatory required, can be modified by different daemons
	MatureHeight = MatureRound * BlockCheckRound // just for calculating the immature balance
)

PoW const

View Source
const (
	// TxMaxExtraSize 1 << 20 = 1024K = 1M, if more than 1m, extra should be separated and using more than one append
	TxMaxExtraSize = 1 << 20
	// TimestampSize is The length of a timestamp bytes
	TimestampSize = 8
	// HashSize is the length of a hash bytes
	HashSize = 32
	// DiffSize is the length of a difficulty
	DiffSize = 32
	// NonceSize is the length of a nonce bytes
	NonceSize = 8 // nonce uses 8 bytes

	// PrivSize is the length of one private key in bytes
	PrivSize = 32
	// AddressSize some for tx
	AddressSize = 35
	// SignatureSize is the size used by signature and is 64 bytes(R 32 + S 32)
	SignatureSize = 64
)

Maximum sizes

View Source
const (
	FloatNG = 1_000_000_000_000_000_000.0
)

Unit const

View Source
const (
	GenesisAddressBase58 = "2Reeyjud1sS7Pq5BMtsK3pSmDnJPfaz4jiffTWwmJdzBvTbq"
)

GenesisAddressBase58 is the genesis address in base58 str FIXME: before initializing new network, should manually init PK & Sign

use genesistool tool to check and generate valid values

Variables

View Source
var (
	// ErrInvalidPoWRawLen means the length of the PoW raw is not 153 bytes
	ErrInvalidPoWRawLen = errors.New("wrong length of PoW raw bytes")
	ErrBlockNoGen       = errors.New("the first tx in one block is required to be a generate tx")
	ErrBlockOnlyOneGen  = errors.New("tx should have only one tx")

	ErrBlockNoHeader          = errors.New("block header is nil")
	ErrBlockDiffInvalid       = errors.New("invalid block diff")
	ErrBlockPrevHashInvalid   = errors.New("invalid block prev hash")
	ErrBlockTxTrieHashInvalid = errors.New("invalid block tx trie hash")
	ErrBlockTimestampInvalid  = errors.New("invalid block timestamp")

	ErrBlockNotSealed = errors.New("the block is not sealed")
)
View Source
var (
	ErrBlockSealBare = errors.New("sealing a bare block")
	ErrInvalidNonce  = errors.New("nonce is invalid")
)
View Source
var (
	GenesisAddress, _ = NewAddressFromBS58(GenesisAddressBase58)
	AvailableNetworks = []Network{
		ZERONET,
		TESTNET,
	}
)

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 (
	// ErrTxSignInvalid occurs when the signature of the Tx doesnt match the Tx 's caller/account
	ErrTxSignInvalid    = errors.New("signer of tx is not the own of the account")
	ErrTxUnsigned       = errors.New("unsigned tx")
	ErrInvalidPublicKey = errors.New("invalid public key")

	ErrTxNoHeader            = errors.New("tx header is nil")
	ErrTxTypeInvalid         = errors.New("invalid tx type")
	ErrTxConvenerInvalid     = errors.New("invalid tx convener")
	ErrTxParticipantsInvalid = errors.New("invalid tx participants")
	ErrTxValuesInvalid       = errors.New("invalid tx values")
	ErrTxFeeInvalid          = errors.New("invalid tx fee")
	ErrTxExtraInvalid        = errors.New("invalid tx extra")
	ErrTxExtraExcess         = errors.New("the size of the tx extra is too large")
)

Errors for Tx

View Source
var ErrHashSize = errors.New("the length of hash is wrong ")
View Source
var ErrInvalidDiff = errors.New("failed to parse blockHeader's difficulty")

ErrInvalidDiff means the diff cannot load from the string

View Source
var ErrNotBlockHeader = errors.New("not a block header")

ErrNotBlockHeader means the var is not a block header

View Source
var ErrRewardInvalid = errors.New("block reward is invalid")
View Source
var (

	// MaxTarget is the Max value of mining 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))

RegisterFee is the fee for registering a new account

Functions

func GetBlockReward

func GetBlockReward(height uint64) *big.Int

GetBlockReward returns the block reward in a specific height reward = 2 + 8*(0.9)^Era

func GetEmptyHash

func GetEmptyHash() []byte

GetEmptyHash return an empty hash

func GetGenesisBlockNonce

func GetGenesisBlockNonce(network Network) []byte

func GetGenesisGenerateTxSignature

func GetGenesisGenerateTxSignature(network Network) []byte

func GetGenesisTimestamp

func GetGenesisTimestamp(network Network) uint64

GetGenesisTimestamp returns the genesis timestamp must be the time chain started, or the difficulty algo wont work FIXME: should be the time network starts

func GetMatureHeight

func GetMatureHeight(currentHeight uint64) uint64

GetMatureHeight will return the next mature height for now

it is 100 * X

func GetNextDiff

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

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

Types

type Account

type Account struct {
	Num      uint64
	Owner    []byte
	Contract []byte
	Context  *AccountContext
}

Account is the shell of the address to process the txs and contracts

func GetGenesisStyleAccount

func GetGenesisStyleAccount(num AccountNum) *Account

GetGenesisStyleAccount will return the genesis style account.

func NewAccount

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

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

func (*Account) Equals

func (x *Account) Equals(other *Account) (bool, error)

Equals returns whether the other is equals to the Account

func (*Account) MarshalJSON

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

MarshalJSON converts the Account into json bytes

func (*Account) UnmarshalJSON

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

UnmarshalJSON recovers the Account from the json bytes

type AccountContext

type AccountContext struct {
	Keys   []string
	Values [][]byte
	// contains filtered or unexported fields
}

AccountContext is the Context field of the Account, which is a in-mem (on-chain) k-v storage

func NewAccountContext

func NewAccountContext() *AccountContext

NewAccountContext craetes a new empty AccountContext

func (*AccountContext) Equals

func (ctx *AccountContext) Equals(other *AccountContext) (bool, error)

Equals checks whether the other is same with this AccountContext

func (*AccountContext) Get

func (ctx *AccountContext) Get(key string) []byte

Get the value by key

func (*AccountContext) MarshalJSON

func (ctx *AccountContext) MarshalJSON() ([]byte, error)

MarshalJSON encodes the context as a map, with hex-encoded values

func (*AccountContext) Set

func (ctx *AccountContext) Set(key string, val []byte)

Set the k-v data

func (*AccountContext) UnmarshalJSON

func (ctx *AccountContext) UnmarshalJSON(raw []byte) error

UnmarshalJSON decodes the AccountContext from the map with hex values

type AccountNum

type AccountNum uint64

AccountNum is a uint64 number which used as the identifier of the Account

func NewNumFromBytes

func NewNumFromBytes(b []byte) AccountNum

NewNumFromBytes recovers the AccountNum from the bytes in LE

func (AccountNum) Bytes

func (num AccountNum) Bytes() []byte

Bytes convert the uint64 AccountNum into bytes in LE

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)

NewAddressFromBS58 converts a base58 string into the Address

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

BS58 generates the base58 string representing the Address

func (Address) MarshalJSON

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

MarshalJSON makes the base58 string as the Address' json value

func (Address) PubKey

func (a Address) PubKey() secp256k1.PublicKey

PubKey gets the public key from address for validation

func (Address) String

func (a Address) String() string

func (*Address) UnmarshalJSON

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

UnmarshalJSON recovers the Address from the base58 string json value

type AppendExtra

type AppendExtra struct {
	Pos     uint64
	Content []byte
}

AppendExtra is the pre-defined data strcut for the Extra field in Append Tx

type Balance

type Balance struct {
	Address Address
	Amount  *big.Int
}

Balance is a unit in Sheet.Balances, which represents the remaining coin amount of the address

type Block

type Block struct {
	Header *BlockHeader
	Txs    []*Tx
	Subs   []*BlockHeader
}

Block is the base unit of the block chain and the container of the txs, which provides the safety assurance by the hashes in the header

func GetGenesisBlock

func GetGenesisBlock(network Network) *Block

GetGenesisBlock will return a complete sealed GenesisBlock.

func NewBareBlock

func NewBareBlock(network Network, height uint64, blockTime uint64, 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 NewBlock

func NewBlock(network Network, height uint64, timestamp uint64, prevBlockHash, txTrieHash, subTrieHash, difficulty,
	nonce []byte, txs []*Tx, subs []*BlockHeader) *Block

NewBlock creates a new Block

func NewBlockFromHeader

func NewBlockFromHeader(blockHeader *BlockHeader, txs []*Tx, subs []*BlockHeader) *Block

NewBlockFromHeader creates a new Block

func NewBlockFromPoWRaw

func NewBlockFromPoWRaw(raw []byte, txs []*Tx, subs []*BlockHeader) (*Block, error)

NewBlockFromPoWRaw 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) Equals

func (x *Block) Equals(other *Block) (bool, error)

func (*Block) GetActualDiff

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

GetActualDiff returns the diff decided by nonce.

func (*Block) GetHash

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

GetHash will help you get the hash of block.

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) GetPrevHash

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

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

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)

MarshalJSON encodes the Block into the json bytes

func (*Block) PowHash

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

PowHash will help you get the pow hash of block.

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) error

ToUnsealing converts a bare block to an unsealing block

func (*Block) UnmarshalJSON

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

UnmarshalJSON decode the Block from the json bytes

type BlockHeader

type BlockHeader struct {
	Network Network // 1

	Height    uint64 // 4
	Timestamp uint64 // 4

	PrevBlockHash []byte // 32
	TxTrieHash    []byte // 32
	SubTrieHash   []byte // 32

	Difficulty []byte // 32
	Nonce      []byte `rlp:"tail"` // 8
}

BlockHeader is the fix-sized header of the block, which is able to describe itself.

func (*BlockHeader) CalculateHash

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

CalculateHash calcs the hash of the Block header with sha3_256, aiming to get the merkletree hash when summarizing subs into the header.

func (*BlockHeader) Equals

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

Equals checks whether the block headers equal

type DeleteExtra

type DeleteExtra struct {
	Pos     uint64
	Content []byte
}

DeleteExtra is the pre-defined data struct for the Extra field in Delete Tx

type HeaderTrie

type HeaderTrie []*BlockHeader

HeaderTrie is a fixed ordered block header container of the subBlocks

func NewHeaderTrie

func NewHeaderTrie(headers []*BlockHeader) HeaderTrie

NewHeaderTrie creates new HeaderTrie

func (*HeaderTrie) Contains

func (ht *HeaderTrie) Contains(h *BlockHeader) bool

Contains determine if tt.Txs and tx are equal.

func (*HeaderTrie) TrieRoot

func (ht *HeaderTrie) TrieRoot() []byte

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

type Network

type Network uint8

Network is the type of the ngchain network

const (
	// ZERONET is the local regression testnet
	ZERONET Network = 0
	// TESTNET is the public internet testnet
	TESTNET Network = 1
	// MAINNET is the public network for production
	MAINNET Network = 2
)

func GetNetwork

func GetNetwork(netName string) Network

GetNetwork converts the network name to the Network type

func (Network) String

func (net Network) String() string

type Sheet

type Sheet struct {
	Network   Network
	Height    uint64
	BlockHash []byte
	Balances  []*Balance
	Accounts  []*Account
}

func GetGenesisSheet

func GetGenesisSheet(network Network) *Sheet

GetGenesisSheet returns a genesis sheet

func NewSheet

func NewSheet(network Network, height uint64, blockHash []byte, balances []*Balance, accounts []*Account) *Sheet

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

type Tx

type Tx struct {
	Network      Network
	Type         TxType
	Height       uint64 // lock the tx on the specific height, rather than the hash, to make the tx can act on forking
	Convener     AccountNum
	Participants []Address
	Fee          *big.Int
	Values       []*big.Int // each value is a free-length slice

	Extra []byte
	Sign  []byte `rlp:"optional"`
}

Tx is the basic transaction, or operation, in ngchain network

func GetGenesisGenerateTx

func GetGenesisGenerateTx(network Network) *Tx

GetGenesisGenerateTx provides the genesis generate tx under current network

func NewTx

func NewTx(network Network, txType TxType, height uint64, convener AccountNum, participants []Address, values []*big.Int, fee *big.Int,
	extraData, sign []byte) *Tx

NewTx is the default constructor for ngtypes.Tx

func NewUnsignedTx

func NewUnsignedTx(network Network, txType TxType, height uint64, convener AccountNum, participants []Address, 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) CheckDelete

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

CheckDelete does a self check for delete tx

func (*Tx) CheckDestroy

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

CheckDestroy does a self check for destroy tx

func (*Tx) CheckGenerate

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

CheckGenerate does a self check for generate 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) Equals

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

Equals mainly for calculating the tire root of txs.

func (*Tx) GetHash

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

GetHash mainly for calculating the tire root of txs and sign tx. The returned hash is sha3_256(tx_with_sign)

func (*Tx) GetUnsignedHash

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

GetUnsignedHash mainly for signing and verifying. The returned hash is sha3_256(tx_without_sign)

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) ManuallySetSignature

func (x *Tx) ManuallySetSignature(sign []byte)

func (*Tx) MarshalJSON

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

MarshalJSON encodes the tx into the json bytes

func (*Tx) Signature

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

Signature will re-sign the Tx with private key.

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

UnmarshalJSON decodes the Tx from the json bytes

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 []*Tx

TxTrie is a fixed ordered tx container to get the trie root hash. This is not thread-safe

func NewTxTrie

func NewTxTrie(txs []*Tx) TxTrie

NewTxTrie receives ordered ops.

func (*TxTrie) Contains

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

Contains determine if tt.Txs and tx are equal.

func (*TxTrie) TrieRoot

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

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

type TxType

type TxType uint8
const (
	InvalidTx TxType = iota
	GenerateTx
	RegisterTx
	DestroyTx // renamed from logout

	TransactTx

	AppendTx // add content to the tail of contract
	DeleteTx

	LockTx   // TODO: cannot assign nor append, but can run vm
	UnlockTx // TODO: disable vm, but enable assign and append
)

Jump to

Keyboard shortcuts

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