utxo

package
v0.0.0-...-b124b1e Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2022 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package utxo is the key part of XuperChain, this module keeps all Unspent Transaction Outputs.

For a transaction, the UTXO checks the tokens used in reference transactions are unspent, and reject the transaction if the initiator doesn't have enough tokens. UTXO also checks the signature and permission of transaction members.

Index

Constants

View Source
const (
	UTXOLockExpiredSecond = 60
	LatestBlockKey        = "pointer"
	UTXOCacheSize         = 100000
	OfflineTxChanBuffer   = 100000

	// TxVersion 为所有交易使用的版本
	TxVersion = 3

	FeePlaceholder = "$"
	UTXOTotalKey   = "xtotal"
)

package constants

Variables

View Source
var (
	ErrNoEnoughUTXO        = errors.New("no enough money(UTXO) to start this transaction")
	ErrUTXONotFound        = errors.New("this utxo can not be found")
	ErrInputOutputNotEqual = errors.New("input's amount is not equal to output's")
	ErrUnexpected          = errors.New("this is a unexpected error")
	ErrNegativeAmount      = errors.New("amount in transaction can not be negative number")
	ErrUTXOFrozen          = errors.New("utxo is still frozen")
	ErrUTXODuplicated      = errors.New("found duplicated utxo in same tx")
)

常用VM执行错误码

Functions

func GenUtxoKey

func GenUtxoKey(addr []byte, txid []byte, offset int32) string

func GenUtxoKeyWithPrefix

func GenUtxoKeyWithPrefix(addr []byte, txid []byte, offset int32) string

GenUtxoKeyWithPrefix generate UTXO key with given prefix

func MakeUtxoKey

func MakeUtxoKey(key []byte, amount string) *protos.UtxoKey

func TopSortDFS

func TopSortDFS(g TxGraph) (order []string, cyclic bool, childDAGSize []int)

TopSortDFS 对依赖关系图进行拓扑排序 输入:依赖关系图,就是个map 输出: order: 排序后的有序数组,依赖者排在前面,被依赖的排在后面

cyclic: 如果发现有环形依赖关系则输出这个数组

实现参考: https://rosettacode.org/wiki/Topological_sort#Go 在我们映射中,RefTx是边的源点

Types

type CacheFiller

type CacheFiller struct {
	// contains filtered or unexported fields
}

func (*CacheFiller) Add

func (cf *CacheFiller) Add(f func())

func (*CacheFiller) Commit

func (cf *CacheFiller) Commit()

type CacheItem

type CacheItem struct {
	UtxoItem
	// contains filtered or unexported fields
}

type InboundTx

type InboundTx struct {
	// contains filtered or unexported fields
}

InboundTx is tx wrapper

type LockKey

type LockKey struct {
	// contains filtered or unexported fields
}

LockKey is a lock item with lock type and key

func (*LockKey) String

func (lk *LockKey) String() string

String returns readable string for a lock item

type SpinLock

type SpinLock struct {
	// contains filtered or unexported fields
}

SpinLock is a collections of small locks on special keys

func NewSpinLock

func NewSpinLock() *SpinLock

NewSpinLock returns a new spinlock instance

func (*SpinLock) ExtractLockKeys

func (sp *SpinLock) ExtractLockKeys(tx *protos.Transaction) []*LockKey

ExtractLockKeys extract lock items from a transaction

func (*SpinLock) IsLocked

func (sp *SpinLock) IsLocked(key string) bool

IsLocked returns whether a key is locked

func (*SpinLock) TryLock

func (sp *SpinLock) TryLock(lockKeys []*LockKey) ([]*LockKey, bool)

TryLock try to lock some keys

func (*SpinLock) Unlock

func (sp *SpinLock) Unlock(lockKeys []*LockKey)

Unlock release the locks on some keys

type TxGraph

type TxGraph map[string][]string

交易依赖关系图

type TxLists

type TxLists []*protos.Transaction

type UTXOSandbox

type UTXOSandbox struct {
	// contains filtered or unexported fields
}

func NewUTXOSandbox

func NewUTXOSandbox(cfg *base.SandboxConfig) *UTXOSandbox

func (*UTXOSandbox) GetUTXORWSets

func (uc *UTXOSandbox) GetUTXORWSets() *base.UTXORWSet

func (*UTXOSandbox) Transfer

func (u *UTXOSandbox) Transfer(from, to string, amount *big.Int) error

type UtxoCache

type UtxoCache struct {
	// <ADDRESS, <UTXO_KEY, UTXO_ITEM>>
	Available map[string]map[string]*CacheItem
	All       map[string]map[string]*CacheItem
	List      *list.List
	Limit     int
	// contains filtered or unexported fields
}

UtxoCache is a in-memory cache of UTXO

func NewUtxoCache

func NewUtxoCache(limit int) *UtxoCache

NewUtxoCache create instance of UtxoCache

func (*UtxoCache) Insert

func (uv *UtxoCache) Insert(addr string, utxoKey string, item *UtxoItem)

Insert insert/update utxo cache

func (*UtxoCache) Lock

func (uv *UtxoCache) Lock()

Lock used to lock cache

func (*UtxoCache) Remove

func (uv *UtxoCache) Remove(address string, utxoKey string)

Remove delete uxto key from cache

func (*UtxoCache) Unlock

func (uv *UtxoCache) Unlock()

Unlock used to unlock cache

func (*UtxoCache) Use

func (uv *UtxoCache) Use(address string, utxoKey string)

Use mark a utxo key as used

type UtxoItem

type UtxoItem struct {
	Amount       *big.Int //utxo的面值
	FrozenHeight int64    //锁定until账本高度超过
}

UtxoItem the data structure of an UTXO item

func (*UtxoItem) Dumps

func (item *UtxoItem) Dumps() ([]byte, error)

Dumps dump UTXO item into JSON encoded data

func (*UtxoItem) Loads

func (item *UtxoItem) Loads(data []byte) error

Loads load UTXO item from JSON encoded data

type UtxoLockItem

type UtxoLockItem struct {
	// contains filtered or unexported fields
}

type UtxoVM

type UtxoVM struct {
	Mutex    *sync.RWMutex // utxo leveldb表读写锁
	MutexMem *sync.Mutex   // 内存锁定状态互斥锁
	SpLock   *SpinLock     // 自旋锁,根据交易涉及的utxo和改写的变量

	UtxoCache *UtxoCache

	OfflineTxChan     chan []*protos.Transaction // 未确认tx的通知chan
	PrevFoundKeyCache *cache.LRUCache            // 上一次找到的可用utxo key,用于加速GenerateTx

	ModifyBlockAddr  string          // 可修改区块链的监管地址
	BalanceCache     *cache.LRUCache //余额cache,加速GetBalance查询
	CacheSize        int             //记录构造utxo时传入的cachesize
	BalanceViewDirty map[string]int  //balanceCache 标记dirty: addr -> sequence of view
	// contains filtered or unexported fields
}

func MakeUtxo

func MakeUtxo(sctx *stateBase.StateCtx, metaHandle *meta.Meta, cachesize, tmplockSeconds int,
	stateDB storage.Database) (*UtxoVM, error)

MakeUtxoVM 这个函数比NewUtxoVM更加可订制化

func NewUtxo

func NewUtxo(sctx *stateBase.StateCtx, metaHandle *meta.Meta, stateDB storage.Database) (*UtxoVM, error)

NewUtxoVM 构建一个UtxoVM对象

@param ledger 账本对象
@param store path, utxo 数据的保存路径
@param xlog , 日志handler

func (*UtxoVM) AddBalance

func (uv *UtxoVM) AddBalance(addr []byte, delta *big.Int)

addBalance 增加cache中的Balance

func (*UtxoVM) CheckInputEqualOutput

func (uv *UtxoVM) CheckInputEqualOutput(tx *protos.Transaction, batch storage.Batch) error

CheckInputEqualOutput 校验交易的输入输出是否相等

func (*UtxoVM) CleanBatchCache

func (uv *UtxoVM) CleanBatchCache(newBatch storage.Batch)

CleanBatchCache clean batch cache when new batch.

func (*UtxoVM) Close

func (uv *UtxoVM) Close()

Close 关闭utxo vm, 目前主要是关闭leveldb

func (*UtxoVM) GetAccountContracts

func (uv *UtxoVM) GetAccountContracts(account string) ([]string, error)

GetAccountContracts get account contracts, return a slice of contract names

func (*UtxoVM) GetBalance

func (uv *UtxoVM) GetBalance(addr string) (*big.Int, error)

获得一个账号的余额,inLock表示在调用此函数时已经对uv.mutex加过锁了

func (*UtxoVM) GetTotal

func (uv *UtxoVM) GetTotal() *big.Int

GetTotal 返回当前vm的总资产

func (*UtxoVM) InsertBatchCache

func (uv *UtxoVM) InsertBatchCache(key, value interface{})

InsertBatchCache inser key value to batch cache.

func (*UtxoVM) NewBatch

func (uv *UtxoVM) NewBatch() storage.Batch

NewBatch return batch instance

func (*UtxoVM) QueryAccountContainAK

func (uv *UtxoVM) QueryAccountContainAK(address string) ([]string, error)

func (*UtxoVM) QueryContractStatData

func (uv *UtxoVM) QueryContractStatData() (*protos.ContractStatData, error)

func (*UtxoVM) QueryUtxoRecord

func (uv *UtxoVM) QueryUtxoRecord(accountName string, displayCount int64) (*protos.UtxoRecordDetail, error)

QueryUtxoRecord query utxo record details

func (*UtxoVM) RemoveBatchCache

func (uv *UtxoVM) RemoveBatchCache(key interface{})

RemoveBatchCache remove key from batch cache.

func (*UtxoVM) RemoveUtxoCache

func (uv *UtxoVM) RemoveUtxoCache(address string, utxoKey string)

RemoveUtxoCache 清理utxoCache

func (*UtxoVM) ScanWithPrefix

func (uv *UtxoVM) ScanWithPrefix(prefix []byte) storage.Iterator

ScanWithPrefix 通过前缀获得一个连续读取的迭代器

func (*UtxoVM) SelectUtxo

func (uv *UtxoVM) SelectUtxo(fromAddr string, totalNeed *big.Int, needLock, excludeUnconfirmed bool) ([]*protos.TxInput, [][]byte, *big.Int, error)

func (*UtxoVM) SelectUtxos

func (uv *UtxoVM) SelectUtxos(fromAddr string, totalNeed *big.Int, needLock, excludeUnconfirmed bool) ([]*protos.TxInput, [][]byte, *big.Int, error)

SelectUtxos 选择足够的utxo 输入: 转账人地址、公钥、金额、是否需要锁定utxo 输出:选出的utxo、utxo keys、实际构成的金额(可能大于需要的金额)、错误码

func (*UtxoVM) SelectUtxosBySize

func (uv *UtxoVM) SelectUtxosBySize(fromAddr string, needLock, excludeUnconfirmed bool) ([]*protos.TxInput, [][]byte, *big.Int, error)

func (*UtxoVM) SetModifyBlockAddr

func (uv *UtxoVM) SetModifyBlockAddr(addr string)

SetModifyBlockAddr set modified block addr

func (*UtxoVM) SubBalance

func (uv *UtxoVM) SubBalance(addr []byte, delta *big.Int)

subBalance 减少cache中的Balance

func (*UtxoVM) UnlockKey

func (uv *UtxoVM) UnlockKey(utxoKey []byte)

解锁utxo key

func (*UtxoVM) UpdateUtxoTotal

func (uv *UtxoVM) UpdateUtxoTotal(delta *big.Int, batch storage.Batch, inc bool)

Jump to

Keyboard shortcuts

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