xginx

package module
v0.0.0-...-ae61dc4 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2020 License: Apache-2.0 Imports: 55 Imported by: 0

README

#xginx by cxuhua@qq.com

如何开始:

//编译 cd server go build -o main

修改配置文件:v1000.json

"data_dir": "数据存储目录",

"tcp_ip": "服务器对外ip地址",

"log_file": "日志文件路径",

"max_conn": 50,//最大连接

启动: ./main -conf=配置文件路径 -debug=true|false(是否处于开发模式)

更新日志

2019-12-13

1.舍弃http服务

2.重新设计了测试区块

2019-12-7

1.交易池添加引用交易索引,账户相关索引

2.增强输入sequence开始支持支付通道

2019-12-4

1.添加txin seq字段,可以覆盖交易池中的交易,需要重新生成区块

2019-12-3

1.添加时间戳获取方法,可自定义当前时间戳

2019-12-2

1.添加了数据包广播头和响应支持

2019-11-30

1.交易池中检测失败的将会被移除

2019-11-29

1.添加了ReadFull和WriteFull防止网络数据读写不完整

2.修正了存在交易费计算merkle的错误

2019-11-27

1.加强MsgGetTxPool消息同步两节点的交易池

2.设计了新的支持多线程的hash方法进行挖矿

2019-11-26

1.交易添加locktime属性表示交易锁定时间,实现在某个高度或者时间交易才能加入打包进区块

2.可以消费交易池中的输出,但是只能在同一个区块中,并且输出必须在之前的交易中

2019-11-25

1.填加钱包账号导出和导入接口,允许选择是否导出私钥

2019-11-23

1.今天挖出了第一个区块,000000007be7626a14398ee03706080d33ac07bb18bb82254331ff6191f8c850

2.添加了区块信息http接口

2019-11-22

1.重新设计了bloom过滤器,代码来自BTC项目

2019-11-21

1.当生成新区块时先发布区块头到周围节点,周围节点再根据头下载区块数据

2.添加基于leveldb的bloom过滤器,线程安全

2019-11-20

1.基本解决分叉问题,按照链高胜出为原则,并且需要提供区块头列表作为证据

2019-11-19

1.锁定脚本可以增加自自定义数据,但大小不能超过4K

2.尚未解决链分叉的情况

2019-11-18

1.添加了区块链迭代器,废弃链上的迭代方法

2019-11-17

1.添加了日志输出方法,LogInfo(f),LogError(f),LogWarn(f)

2.重新修改了数据编码解码方式

2019-11-16

1.添加了交易池,如果一笔金额在未确认的交易池中,下个交易引用将会失败

2.不能消费使用未确认的交易输出了,也就是说不能引用交易池中的交易输出

Documentation

Overview

Package xginx implements a simple multi-topic pub-sub library.

Topics must be strings and messages of any type can be published. A topic can have any number of subcribers and all of them receive messages published on the topic.

Index

Constants

View Source
const (
	//MaxCompressUInt 压缩金额可存储的最大数字
	MaxCompressUInt = uint64(0b1111 << 57)
	//Coin 分割系数 1Coin 可分割1000份
	Coin = Amount(1000)
	// MaxMoney < MaxCompressUInt
	MaxMoney = 21000000 * Coin
)

金额定义

View Source
const (
	//最大块大小
	MaxBlockSize = 1024 * 1024 * 8
	//最大日志大小
	MaxLogSize = 1024 * 1024 * 4
	//最大执行脚本长度
	MaxExecSize = 1024 * 2
	//最大meta数据长度
	MaxMetaSize = 1024 * 4
	//默认: 50步,1=30毫秒
	DefaultExeLimit = (30 << 16) | 30000
	//高16位限制执行步数,低16位限制执行时间,单位:微秒
	MaxExeTimeLimit = uint32(0xFFFF) //65毫秒
	MaxExeStepLimit = uint32(30000)  //6万step
	//coinbase需要100区块后可用
	CoinbaseMaturity = 100
	//如果所有的输入全是 >= FinalSequence,交易立即生效
	FinalSequence = VarUInt(0xFFFFFF)
)

常量定义

View Source
const (
	//如果是新出的区块设置此标记并广播
	MsgBlockNewFlags = 1 << 0
	//使用Bytes原始字节打包传输
	MsgBlockUseBytes = 1 << 1
	//使用Blk对象打包传输
	MsgBlockUseBlk = 1 << 2
)

区块消息标记

View Source
const (
	MaxBloomFilterSize = 36000
	MaxHashFuncs       = 50
	Ln2Squared         = 0.4804530139182014246671025263266649717305529515945455
)

布隆过滤器定义

View Source
const (
	//NoExpiration For use with functions that take an expiration time.
	NoExpiration time.Duration = -1
	//DefaultExpiration For use with functions that take an expiration time. Equivalent to
	// passing in the same expiration duration as was given to New() or
	// NewFrom() when the cache was created (e.g. 5 minutes.)
	DefaultExpiration time.Duration = 0
)
View Source
const (
	ClientIn  = 1
	ClientOut = 2
)

连接类型

View Source
const (
	//交易脚本
	ExecTypeTxMain = "TxMain"
	//输\入脚本
	ExecTypeInMain = "InMain"
	//输出脚本
	ExecTypeOutMain = "OutMain"
)

脚本类型

View Source
const (
	//金额账户
	CoinAccountType = 1
	//临时账户
	TempAccountType = 2
)
View Source
const (
	//矿工操作 MinerAct
	NewMinerActTopic = "NewMinerAct"
	//更新了一个区块数据 BlockInfo
	NewLinkBlockTopic = "NewLinkBlock"
	//接收的广播区块
	NewRecvBlockTopic = "NewRecvBlock"
	//当交易池中的交易被移除时 txid
	TxPoolDelTxTopic = "TxPoolDelTx"
	//每隔多少秒打印挖掘状态
	MinerLogSeconds = 5
)

订阅消息类型

View Source
const (
	//开始挖矿操作 args(uint32) = block ver
	OptGenBlock = iota
	//停止当前区块创建
	OptStopGenBlock
	//发送一个区块头数据进行验证 args = HeaderBytes
	OptSendHeadBytes
)

操作定义

View Source
const (
	NtVersion = NTType(1)
	//ping/pong
	NtPing = NTType(2)
	NtPong = NTType(3)
	//获取节点连接的其他地址
	NtGetAddrs = NTType(4)
	NtAddrs    = NTType(5)
	//inv 交易或者区块通报
	//当有新的交易或者区块生成通报给周边的节点
	NtInv = NTType(6)
	//获取交易或者区块
	NtGetInv = NTType(7)
	//获取交易的返回
	NtTx = NTType(8)
	//获取区块的返回
	NtBlock = NTType(9)
	//获取区块按高度
	NtGetBlock = NTType(10)
	//返回区块头列表
	NtHeaders = NTType(11)
	//返回一个错误信息
	NtError = NTType(12)
	//消息通知
	NtAlert = NTType(13)
	//过滤器 加载 添加 清除
	NtFilterLoad  = NTType(14)
	NtFilterAdd   = NTType(15)
	NtFilterClear = NTType(16)
	//交易merkle树
	NtGetMerkle = NTType(17)
	NtTxMerkle  = NTType(18)
	//获取内存交易池
	NtGetTxPool = NTType(19)
	NtTxPool    = NTType(20)
	//广播包头和响应,当广播消息时只发送广播包头,收到包头如果确定无需要收取数据再请求包数据
	NtBroadPkg = NTType(0xf0)
	NtBroadAck = NTType(0xf1)
)

协议包标识

View Source
const (
	ErrCodeRecvBlock  = 100001
	ErrCodeRecvTx     = 100002
	ErrCodeFilterMiss = 100003
	ErrCodeFilterLoad = 100004
	ErrCodeTxMerkle   = 100005
	ErrCodeBlockMiss  = 100006
	ErrCodeHeaders    = 100007
)

消息错误代码

View Source
const (
	InvalidArb            = ^uint8(0) //无效的仲裁
	ScriptCoinbaseType    = uint8(0)  //coinbase script
	ScriptLockedType      = uint8(1)  //标准锁定脚本 用于输出
	ScriptWitnessType     = uint8(2)  //隔离见证多重签名脚本 用于输入
	ScriptTxType          = uint8(3)  //交易脚本 用于控制交易是否打包进区块,是否进入交易池,是否发布上网
	MaxCoinbaseScriptSize = 256       //最大coinbase脚本长度
)

脚本类型定义 Script 第一个字节表示脚本类型

View Source
const (
	//收到所有消息
	NetMsgTopic = "NetMsg"
	//创建了新的交易进入了交易池
	NewTxTopic = "NewTx"
	//默认端口
	DefaultPort = uint16(9333)
)

消息订阅

View Source
const (
	//公钥长度
	PublicKeySize = 33
	//偶数公钥前缀
	P256PubKeyEven = byte(0x02)
	//奇数公钥前缀
	P256PubKeyOdd = byte(0x03)
	//公钥ID前缀
	PublicIDPrefix = "pk"
	//地址前缀
	AddressPrefix = "st"
)

公钥定义

View Source
const (
	//交易类型
	InvTypeTx = uint8(1)
	//块类型
	InvTypeBlock = uint8(2)
)

inv类型定义

View Source
const (
	//MaxTxPoolSize 交易池最大数量
	MaxTxPoolSize = 4096 * 4
	//TxPoolFile 交易池数据保存文件
	TxPoolFile = "txpool.dat"
)

交易池最大数量

View Source
const (
	AccountKeyMaxSize = 16
)

账号最大的私钥数量

View Source
const (
	//全节点
	FullNodeFlag = 1 << 0
)

节点类型定义

View Source
const (
	// 无效的块高度
	InvalidHeight = ^uint32(0)
)

定义高度

View Source
const (
	MapKeyFilter = "BloomFilter"
)

属性名称

View Source
const (
	//PackageAttrZip 数据是否启用压缩
	PackageAttrZip = uint8(1 << 0)
)

数据包属性

View Source
const (
	//RSABits 默认rsa加密强度
	RSABits = 2048
)
View Source
const Ripemd160BlockSize = 64

Ripemd160BlockSize The block size of the hash algorithm in bytes.

View Source
const Ripemd160Size = 20

Ripemd160Size The size of the checksum in bytes.

View Source
const (
	UInt256Width = 256 / 32
)

hash宽度

Variables

View Source
var (
	BitcoinAlphabet = NewAlphabet("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
	IPFSAlphabet    = NewAlphabet("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
	FlickrAlphabet  = NewAlphabet("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")
	RippleAlphabet  = NewAlphabet("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")
)

Alphabet: copy from https://en.wikipedia.org/wiki/Base58

View Source
var (
	BestBlockKey = []byte("BestBlockKey") //最高区块数据保存key
	InvalidBest  = NewInvalidBest()       //无效的状态
)

区块定义

View Source
var (
	//ErrArriveFirstBlock 到达第一个
	ErrArriveFirstBlock = errors.New("arrive first block")
	//ErrEmptyBlockChain 空链
	ErrEmptyBlockChain = errors.New("this is empty chain")
	//ErrHeadersScope 当获取到的区块头在链中无法找到时
	ErrHeadersScope = errors.New("all hds not in scope")
	//ErrHeadersTooLow 证据区块头太少
	ErrHeadersTooLow = errors.New("headers too low")
)

错误定义

View Source
var (
	ConfFile = flag.String("conf", "v10000.json", "config file name")
	IsDebug  = flag.Bool("debug", true, "startup mode")
)

启动参数

View Source
var (
	//DefaultTxScript 默认交易脚本 控制是否能进入区块
	DefaultTxScript = []byte(`return true`)
	//DefaultInputScript 默认输入脚本 控制是否能消费
	DefaultInputScript = []byte(`return true`)
	//DefaultLockedScript 默认锁定脚本 控制消费输出需要的条件
	//验证地址和签名
	DefaultLockedScript = []byte(`return verify_addr() and verify_sign()`)
)
View Source
var (
	ErrDataSize = errors.New("size data error")
	Endian      = binary.LittleEndian
	ErrVarSize  = errors.New("var size too big")
	ZERO256     = HASH256{}
	ZERO160     = HASH160{}
)

hash定义

View Source
var (
	ErrNotID = errors.New("msg not id,can't broad")
	ErrMsgID = MsgID{}
)

错误定义

View Source
var (
	PrefixSecretKey = []byte{128}
	PKBytesZero     = PKBytes{}
	SigBytesZero    = SigBytes{}
)

算法

View Source
var (
	BlockPrefix = []byte{1} //块头信息前缀 ->blkmeta
	TxsPrefix   = []byte{2} //tx 所在区块前缀 ->blkid+txidx
	CoinsPrefix = []byte{3} //账户可用金额存储 pkh_txid_idx -> amount
	TxpPrefix   = []byte{4} //账户相关交易索引 按高度排序  pkh_height(big endian)_txid -> blkid+txidx
)

数据前缀定义

View Source
var (
	//AutoGenBlockTime 自动创建区块时间
	AutoGenBlockTime = time.Second * 30
)
View Source
var (
	//CoinSplit 1个coin可分割为1000份
	CoinSplit = decimal.NewFromInt(int64(Coin))
)
View Source
var DocumentIDLen = len(NilDocumentID)
View Source
var (
	//ErrCheckSum 校验和错误,一般密码错误会出现这个问题
	ErrCheckSum = errors.New("check sum error, maybe password error")
)
View Source
var (
	//需要切换到下一个文件存储
	ErrNextFile = errors.New("next file")
)

错误

View Source
var (
	ErrorInvalidBase58String = errors.New("invalid base58 string")
)

Errors

View Source
var (
	Miner = newMinerEngine()
)

默认矿工处理

View Source
var (
	Separator = string(os.PathSeparator)
)

系统路径分隔符

View Source
var (
	Server = NewTCPServer()
)

默认服务

Functions

func AesDecrypt

func AesDecrypt(block cipher.Block, data []byte) ([]byte, error)

AesDecrypt AES解密

func AesEncrypt

func AesEncrypt(block cipher.Block, data []byte) ([]byte, error)

AesEncrypt AES加密

func B58Decode

func B58Decode(input string, alphabet *Alphabet) ([]byte, error)

B58Decode docode with custom alphabet

func B58Encode

func B58Encode(input []byte, alphabet *Alphabet) string

B58Encode encode with custom alphabet

func BECH32Decode

func BECH32Decode(adr string) (string, []byte, error)

BECH32Decode takes a bech32 encoded string and returns the hrp and the full-height data. Can error out for various reasons, mostly problems in the string given. Doesn't do anything segwit specific.

func BECH32Encode

func BECH32Encode(hrp string, data []byte) string

BECH32Encode takes regular bytes of data, and an hrp prefix, and returns the bech32 encoded string. It doesn't do any segwit specific encoding.

func BestValueBytes

func BestValueBytes(id HASH256, h uint32) []byte

BestValueBytes 编码区块状态数据

func ByteSquasher

func ByteSquasher(input []byte, inputWidth, outputWidth uint32) ([]byte, error)

ByteSquasher squashes full-width (8-bit) bytes into "squashed" 5-bit bytes, and vice versa. It can operate on other widths but in this package only goes 5 to 8 and back again. It can return an error if the squashed input you give it isn't actually squashed, or if there is padding (trailing q characters) when going from 5 to 8

func Bytes5to8

func Bytes5to8(input []byte) ([]byte, error)

Bytes5to8 goes from squashed bytes to full height bytes

func Bytes8to5

func Bytes8to5(input []byte) []byte

Bytes8to5 extends a byte slice into a longer, padded byte slice of 5-bit elements where the high 3 bits are all 0.

func CalcBloomFilterSize

func CalcBloomFilterSize(elements int, fprate float64) (uint32, uint32)

CalcBloomFilterSize 结算需要的存储量和hash次数

func CalculateWorkRequired

func CalculateWorkRequired(ct uint32, pt uint32, pw uint32) uint32

CalculateWorkRequired 计算工作难度 ct = lastBlock blockTime pt = lastBlock - 2016 + 1 blockTime pw = lastBlock's bits

func CheckAccountArgs

func CheckAccountArgs(num uint8, less uint8, arbon bool, pkl int) error

CheckAccountArgs 检测账户参数

func CheckExeLimit

func CheckExeLimit(v uint32) error

CheckExeLimit 检测

func CheckProofOfWork

func CheckProofOfWork(hash HASH256, bits uint32) bool

CheckProofOfWork whether a block hash satisfies the proof-of-work requirement specified by nBits

func CheckProofOfWorkBits

func CheckProofOfWorkBits(bits uint32) bool

CheckProofOfWorkBits 检测难度值是否正确

func CheckScript

func CheckScript(codes ...[]byte) error

CheckScript 检测脚本是否有错

func CloseTestBlock

func CloseTestBlock(bi *BlockIndex)

CloseTestBlock 关闭测试用区块链

func CompressUInt

func CompressUInt(n uint64) uint64

CompressUInt 压缩一个整形 max : 60 bits

func CreateChecksum

func CreateChecksum(hrp string, data []byte) []byte

CreateChecksum makes a 6-shortbyte checksum from the HRP and data parts

func DecodeSquashed

func DecodeSquashed(adr string) (string, []byte, error)

DecodeSquashed is the same as Decode, but will return squashed 5-bit high data.

func DecompressUInt

func DecompressUInt(x uint64) uint64

DecompressUInt 解压整形max : 60 bits

func DecompressY

func DecompressY(x *big.Int, ybit uint) *big.Int

DecompressY 为压缩公钥计算y y^2 = x^3 + b y = sqrt(x^3 + b)

func DefaultNewBlock

func DefaultNewBlock(lis IListener, blk *BlockInfo) error

OnNewBlock 当块创建完毕 默认创建coinbase交易加入区块为区块第一个交易

func DefaultkFinished

func DefaultkFinished(blk *BlockInfo) error

OnFinished 完成区块 交易加入完成,在计算难度前

func EncodeAddressWithPrefix

func EncodeAddressWithPrefix(prefix string, pkh HASH160) (string, error)

EncodeAddressWithPrefix 编码地址用指定前缀

func EncodePublicHash

func EncodePublicHash(pkh HASH256) (string, error)

EncodePublicHash 编码公钥hash

func EncodeSquashed

func EncodeSquashed(hrp string, data []byte) string

EncodeSquashed takes the hrp prefix, as well as byte data that has already been squashed to 5-bits high, and returns the bech32 encoded string. It does not return an error; if you give it non-squashed data it will return an empty string.

func EndianUInt32

func EndianUInt32(u32 uint32) []byte

EndianUInt32 用于排序

func EndianUInt64

func EndianUInt64(u64 uint64) []byte

EndianUInt64 用于排序

func FixExeLimit

func FixExeLimit(v uint32) uint32

FixExeLimit 修正执行时间和步数

func GenPrivateKey

func GenPrivateKey() (k *big.Int, err error)

GenPrivateKey 自动生成私钥

func GetContext

func GetContext() context.Context

GetContext 获取区块链服务context

func GetDBKey

func GetDBKey(p []byte, ids ...[]byte) []byte

GetDBKey 获取存储key

func GetExeLimit

func GetExeLimit(v uint32) (int, time.Duration)

ParseExeLimit 解析执行时间和步数

func GetHRP

func GetHRP(adr string) (string, error)

GetHRP Segwit addresses can't be used in Encode and Decode directly, because the witness version is special and doesn't get squashed. GetHRP gets the HRP without checking any validity.

func GetMinPowBits

func GetMinPowBits() uint32

GetMinPowBits Minimum difficulty

func HRPExpand

func HRPExpand(input string) []byte

HRPExpand turns the human redable part into 5bit-bytes for later processing

func Hash160

func Hash160(b []byte) []byte

Hash160 使用Ripemd160进行hash160计算

func Hash256

func Hash256(b []byte) []byte

Hash256 sha256 double

func HashDump

func HashDump(b []byte, pass ...string) (string, error)

HashDump 将数据导出并添加校验,pass存在将进行加密

func HashLoad

func HashLoad(s string, pass ...string) ([]byte, error)

HashLoad HashDump 返回的进行解密和校验

func HexDecode

func HexDecode(s string) []byte

HexDecode hex解码

func HexToBytes

func HexToBytes(s string) []byte

HexToBytes hex解码

func LinkGenesis

func LinkGenesis(bi *BlockIndex)

链接加入创世块

func ListenerLoopAccept

func ListenerLoopAccept(lis net.Listener, connfn func(conn net.Conn) error, errfn func(err error))

开始监听链接

func LogError

func LogError(v ...interface{})

LogError 错误日志

func LogErrorf

func LogErrorf(f string, v ...interface{})

LogErrorf 错误日志带格式化

func LogInfo

func LogInfo(v ...interface{})

LogInfo 信息日志

func LogInfof

func LogInfof(f string, v ...interface{})

LogInfof 信息日志带格式化

func LogWarn

func LogWarn(v ...interface{})

LogWarn 警告日志

func LogWarnf

func LogWarnf(f string, v ...interface{})

LogWarnf 警告日志带格式化

func MurmurHash

func MurmurHash(seed uint32, b []byte) uint32

MurmurHash Murmur Hash算法

func NewAESCipher

func NewAESCipher(key []byte) cipher.Block

NewAESCipher 创建加密算法

func NewRipemd160

func NewRipemd160() hash.Hash

NewRipemd160 returns a new hash.Hash computing the checksum.

func NewTempDir

func NewTempDir() string

NewTempDir 创建一个随机的临时目录

func NewTestOneBlock

func NewTestOneBlock() error

NewTestOneBlock 从交易池获取交易打包区块测试

func NextHeight

func NextHeight(h uint32) uint32

NextHeight 获取下一个高度

func PackExeLimit

func PackExeLimit(step uint32, time uint32) uint32

PackExeLimit 合并限制步数和时间

func ParseExeLimit

func ParseExeLimit(v uint32) (uint32, uint32)

ParseExeLimit 解析执行时间和步数

func PolyMod

func PolyMod(values []byte) uint32

PolyMod takes a byte slice and returns the 32-bit BCH checksum. Note that the input bytes to PolyMod need to be squashed to 5-bits tall before being used in this function. And this function will not error, but instead return an unsuable checksum, if you give it full-height bytes.

func Rand

func Rand(min uint, max uint) uint

Rand ret >= min,ret <= max

func RandUInt32

func RandUInt32() uint32

RandUInt32 获取u32随机值

func ReadFull

func ReadFull(r io.Reader, dp []byte) error

ReadFull 从流读取完整数据

func Ripemd160

func Ripemd160(b []byte) []byte

Ripemd160 hash

func Run

func Run(lis IListener)

Run 启动区块链服务

func SECP256K1

func SECP256K1() elliptic.Curve

SECP256K1 获取secp256k1签名算法

func SegWitAddressDecode

func SegWitAddressDecode(adr string) (string, []byte, error)

SegWitAddressDecode takes a segwit address and returns the pkscript that can go directly into the txout. (includes version byte and data push byte)

func SegWitAddressEncode

func SegWitAddressEncode(hrp string, data []byte) (string, error)

SegWitAddressEncode takes an hrp and data and gives back a segwit address. The data that goes in should be the full pkscript from the txout, including the version byte and the pushdata byte.

func SegWitV0Encode

func SegWitV0Encode(hrp string, data []byte) (string, error)

SegWitV0Encode takes an hrp prefix string and a 20 or 32 byte witness program hash, and turns it into a version 0 address. (it puts the 0 and pushdata in for you.

func SetRandInt

func SetRandInt(v interface{})

SetRandInt 读取随机值

func Sha256

func Sha256(b []byte) []byte

Sha256 sha256 hash

func SipHash

func SipHash(k0, k1 uint64, p []byte) uint64

SipHash sip hash 算法

func SquashedBytesToString

func SquashedBytesToString(input []byte) (string, error)

SquashedBytesToString swaps 5-bit bytes with a string of the corresponding letters

func String

func String(b []byte) string

String 获取以0结束的字符串,\0截断,不包括\0之后的

func StringToSquashedBytes

func StringToSquashedBytes(input string) ([]byte, error)

StringToSquashedBytes uses the inverseCharset to switch from the characters back to 5-bit squashed bytes.

func TimeDays

func TimeDays(d int) time.Duration

TimeDays 获取天

func TimeHour

func TimeHour(d int) time.Duration

TimeHour 获取小时

func TimeMinute

func TimeMinute(d int) time.Duration

TimeMinute 获取分钟

func TimeSecond

func TimeSecond(d int) time.Duration

TimeSecond 获取秒

func TrimAESKey

func TrimAESKey(key []byte) ([]byte, error)

TrimAESKey 整理key为 16 24 or 32

func UR32

func UR32() uint32

UR32 uint32 随机数

func VerifyChecksum

func VerifyChecksum(hrp string, data []byte) bool

VerifyChecksum verify checksum

func WriteFull

func WriteFull(w io.Writer, dp []byte) error

WriteFull 写入完整数据

Types

type Account

type Account struct {
	Num  uint8       //总的密钥数量
	Less uint8       //至少需要签名的数量
	Arb  uint8       //仲裁,当less  < num时可启用,必须是最后一个公钥
	Pubs PublicArray //所有的密钥公钥
	Pris PrivatesMap //公钥对应的私钥,按公钥pkh锁应保存
}

Account 账号地址 可以包含多个签名,但正确签名数量至少是less指定的数量 如果启用了仲裁功能,只需要仲裁签名正确也可以通过签名

func GetTestAccount

func GetTestAccount(bi *BlockIndex) []*Account

GetTestAccount 获取测试用账号

func LoadAccount

func LoadAccount(s string, pass ...string) (*Account, error)

LoadAccount 从导出的数据加载账号

func LoadAccountWithFile

func LoadAccountWithFile(file string, pass ...string) (*Account, error)

LoadAccountWithFile 从文件加载证书

func NewAccount

func NewAccount(num uint8, less uint8, arb bool, pkss ...PKBytes) (*Account, error)

NewAccount 创建num个证书的账号,至少需要less个签名 arb是否启用仲裁 有pkss将不包含私钥

func NewAccountWithPks

func NewAccountWithPks(num uint8, less uint8, arb bool, pkss []PKBytes) (*Account, error)

NewAccountWithPks 创建无私钥账号 不能用来签名

func (Account) Check

func (ap Account) Check() error

Check 检查签名证书数量

func (Account) Dump

func (ap Account) Dump(ispri bool, pass ...string) (string, error)

Dump 导出账号信息 ispri 是否导出私钥

func (Account) DumpWithFile

func (ap Account) DumpWithFile(file string, ispri bool, pass ...string) error

DumpWithFile 导出到文件

func (Account) GetAddress

func (ap Account) GetAddress() (Address, error)

GetAddress 获取账号地址

func (Account) GetPkh

func (ap Account) GetPkh() (HASH160, error)

GetPkh 获取账号地址

func (Account) GetPkhID

func (ap Account) GetPkhID(idx int) (string, error)

获取公钥hash地址ID,当不想公开公钥生成一个收款地址时可以使用这个ID,因为生成地址时只需要公钥hash

func (Account) GetPkhs

func (ap Account) GetPkhs() []HASH160

GetPkhs 获取公钥hash数组

func (Account) GetPks

func (ap Account) GetPks() []PKBytes

GetPks 获取所有的公钥

func (Account) GetPrivateKey

func (ap Account) GetPrivateKey(pi int) *PrivateKey

GetPrivateKey 根据公钥索引获取私钥

func (Account) HasPrivate

func (ap Account) HasPrivate() bool

HasPrivate 是否包含私钥

func (Account) IsEnableArb

func (ap Account) IsEnableArb() bool

IsEnableArb 是否启用仲裁

func (*Account) Load

func (ap *Account) Load(s string, pass ...string) error

Load 加载账号信息

func (Account) NewLockedScript

func (ap Account) NewLockedScript(meta []byte, exec ...[]byte) (Script, error)

NewLockedScript 生成锁定脚本

func (Account) NewWitnessScript

func (ap Account) NewWitnessScript(execs ...[]byte) *WitnessScript

NewWitnessScript 生成未带有签名的脚本对象

func (Account) Sign

func (ap Account) Sign(pi int, hv []byte) (SigBytes, error)

Sign 签名指定公钥

func (Account) SignAll

func (ap Account) SignAll(hv []byte) ([]SigBytes, error)

SignAll 获取账号所有签名

func (Account) SignHash

func (ap Account) SignHash(hash []byte, pri *PrivateKey) (int, SigBytes, error)

SignHash 指定的私钥签名hash 返回账户对应的索引和签名

func (Account) String

func (ap Account) String() string

func (Account) VerifyAll

func (ap Account) VerifyAll(hv []byte, sigs []SigBytes) error

VerifyAll 验证签名

type AccountInfo

type AccountInfo struct {
	Num  int      `json:"num"`  //密钥总数
	Less int      `json:"less"` //需要通过的签名数量
	Arb  bool     `json:"arb"`  //是否启用仲裁 != InvalidArb 表示启用
	Pks  []string `json:"pks"`  //公钥ID
	Desc string   `json:"desc"` //描述
	Type int      `json:"type"` //类型 1-金额账户,2-临时账户,可能会被删除
}

密钥证书存储库 AccountInfo 地址账户,值使用公钥hash256生成地址 无需加密,只是用来保存地址生成数据,是否有控制权需要另外检测

func NewTempAccountInfo

func NewTempAccountInfo(num int, less int, arb bool, pks []string) (*AccountInfo, error)

创建零时账户

func (AccountInfo) Check

func (ka AccountInfo) Check() error

func (*AccountInfo) Decode

func (ka *AccountInfo) Decode(bb []byte) error

func (AccountInfo) Encode

func (ka AccountInfo) Encode() ([]byte, error)

func (AccountInfo) GetArb

func (ka AccountInfo) GetArb() uint8

func (AccountInfo) ID

func (ka AccountInfo) ID() (Address, error)

func (AccountInfo) MustAddress

func (ka AccountInfo) MustAddress() Address

func (AccountInfo) ToAccount

func (ka AccountInfo) ToAccount(db IKeysDB) (*Account, error)

转换为账户,必须拥有私钥控制权

type AccountJSON

type AccountJSON struct {
	Num  uint8    `json:"num"`
	Less uint8    `json:"less"`
	Arb  uint8    `json:"arb"`
	Pubs []string `json:"pubs"`
	Pris []string `json:"pris"`
}

AccountJSON 账户导出结构

type AddrMap

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

AddrMap 地址表

func NewAddrMap

func NewAddrMap() *AddrMap

NewAddrMap 创建地址集合

func (*AddrMap) Get

func (m *AddrMap) Get(a NetAddr) *AddrNode

Get 获取地址

func (*AddrMap) Has

func (m *AddrMap) Has(a NetAddr) bool

Has 是否存在

func (*AddrMap) IncErr

func (m *AddrMap) IncErr(a NetAddr)

IncErr 添加错误次数

func (*AddrMap) Set

func (m *AddrMap) Set(a NetAddr)

Set 设置地址

type AddrNode

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

AddrNode 地址节点

func (AddrNode) IsNeedConn

func (node AddrNode) IsNeedConn() bool

IsNeedConn 是否需要连接

type Address

type Address string

Address 账号地址

const (
	//EmptyAddress 空地址定义
	EmptyAddress Address = ""
)

func EncodeAddress

func EncodeAddress(pkh HASH160) (Address, error)

EncodeAddress 编码地址

func GetAddressWithID

func GetAddressWithID(num uint8, less uint8, arb uint8, ids []string) (Address, error)

GetAddressWithID 根据多个公钥ID生成地址

func (Address) Check

func (a Address) Check() error

Check 检测地址是否正确

func (Address) GetPkh

func (a Address) GetPkh() (HASH160, error)

GetPkh 获取公钥hash

func (Address) NewTxOut

func (a Address) NewTxOut(v Amount, meta []byte, execs ...[]byte) (*TxOut, error)

NewTxOut 创建一个输出

type Alphabet

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

Alphabet The base58 alphabet object.

func NewAlphabet

func NewAlphabet(alphabet string) *Alphabet

NewAlphabet create a custom alphabet from 58-length string. Note: len(rune(alphabet)) must be 58.

func (Alphabet) String

func (alphabet Alphabet) String() string

Alphabet's string representation

type Amount

type Amount int64

Amount 金额类型

func GetCoinbaseReward

func GetCoinbaseReward(h uint32) Amount

GetCoinbaseReward 计算某高度下可获的奖励

func ParseAmount

func ParseAmount(str string) (Amount, error)

ParseAmount 解析金额

func (Amount) Bytes

func (a Amount) Bytes() []byte

Bytes 压缩金额并生成二进制数据

func (*Amount) Decode

func (a *Amount) Decode(r IReader) error

Decode 解码金额,并解压缩

func (Amount) Encode

func (a Amount) Encode(w IWriter) error

Encode 编码并压缩金额

func (*Amount) From

func (a *Amount) From(b []byte) Amount

From 从二进制生成金额

func (Amount) IsRange

func (a Amount) IsRange() bool

IsRange 检测金额是否在有效范围内

func (Amount) String

func (a Amount) String() string

type BIndexIter

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

BIndexIter 区块链迭代器

func (*BIndexIter) Curr

func (it *BIndexIter) Curr() *TBEle

Curr 获取当前区块头

func (*BIndexIter) First

func (it *BIndexIter) First(skip ...int) bool

First 第一个区块

func (*BIndexIter) Height

func (it *BIndexIter) Height() uint32

Height 当前区块高度

func (*BIndexIter) ID

func (it *BIndexIter) ID() HASH256

ID 当前区块id

func (*BIndexIter) Last

func (it *BIndexIter) Last(skip ...int) bool

Last 最后一个区块

func (*BIndexIter) Next

func (it *BIndexIter) Next() bool

Next 下一个区块

func (*BIndexIter) Prev

func (it *BIndexIter) Prev() bool

Prev 上一个区块

func (*BIndexIter) SeekHeight

func (it *BIndexIter) SeekHeight(h uint32, skip ...int) bool

SeekHeight 定位到某个高度

func (*BIndexIter) SeekID

func (it *BIndexIter) SeekID(id HASH256, skip ...int) bool

SeekID 定位到某个区块Id

type Batch

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

Batch 批量写入

func (*Batch) Del

func (b *Batch) Del(ks ...[]byte)

Del 删除

func (*Batch) Dump

func (b *Batch) Dump() []byte

Dump 导出日志

func (*Batch) GetBatch

func (b *Batch) GetBatch() *leveldb.Batch

GetBatch 获取leveldb日志

func (*Batch) GetRev

func (b *Batch) GetRev() *Batch

GetRev 获取写入时的回退日志

func (*Batch) Len

func (b *Batch) Len() int

Len 日志长度

func (*Batch) Load

func (b *Batch) Load(d []byte) error

Load 加载日志

func (*Batch) NewRev

func (b *Batch) NewRev() *Batch

NewRev 设置回退并返回

func (*Batch) Put

func (b *Batch) Put(ks ...[]byte)

Put 最后一个是数据,前面都是key

func (*Batch) Reset

func (b *Batch) Reset()

Reset 重置

type BestValue

type BestValue struct {
	ID     HASH256
	Height uint32
}

BestValue 最优区块

func NewInvalidBest

func NewInvalidBest() BestValue

NewInvalidBest 不合法的区块高度

func (BestValue) Bytes

func (bv BestValue) Bytes() []byte

Bytes 生成二进制数据用于存储

func (BestValue) Curr

func (bv BestValue) Curr() uint32

Curr 获取当前高度

func (*BestValue) From

func (bv *BestValue) From(b []byte) error

From 从二进制数据获取

func (BestValue) IsValid

func (bv BestValue) IsValid() bool

IsValid 高度是否有效

func (BestValue) LastID

func (bv BestValue) LastID() HASH256

LastID 最后一个区块ID

func (BestValue) Next

func (bv BestValue) Next() uint32

Next 获取下一个高度

type BitSet

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

BitSet 位集合

func BitSetFrom

func BitSetFrom(b []byte) *BitSet

BitSetFrom 从指定数据创建位集合

func NewBitSet

func NewBitSet(l int) *BitSet

NewBitSet 创建长度位l的位集合

func (*BitSet) Bytes

func (bs *BitSet) Bytes() []byte

Bytes 获取位集合数据

func (*BitSet) Len

func (bs *BitSet) Len() int

Len 获取位集合长度

func (*BitSet) Set

func (bs *BitSet) Set(i int)

Set 设置位

func (*BitSet) SetTo

func (bs *BitSet) SetTo(i int, v bool)

SetTo 设置位状态

func (*BitSet) Test

func (bs *BitSet) Test(i int) bool

Test 测试位状态

type BlkChunk

type BlkChunk struct {
	ID  VarUInt //数据所在文件id
	Off VarUInt //数据所在位置
	Len VarUInt //数据长度
}

BlkChunk 文件数据状态

func (*BlkChunk) Decode

func (f *BlkChunk) Decode(r IReader) error

Decode 解码数据

func (BlkChunk) Encode

func (f BlkChunk) Encode(w IWriter) error

Encode 编码数据

func (BlkChunk) HasData

func (f BlkChunk) HasData() bool

HasData 是否存在数据

type BlockEvent

type BlockEvent struct {
	Idx *BlockIndex
	Blk *BlockInfo
}

BlockEvent 区块发布交易参数

type BlockHeader

type BlockHeader struct {
	Ver    uint32  //block ver
	Prev   HASH256 //pre block hash
	Merkle HASH256 //txs Merkle tree hash
	Time   uint32  //时间戳
	Bits   uint32  //难度
	Nonce  uint32  //随机值
	// contains filtered or unexported fields
}

BlockHeader 区块头

func (BlockHeader) Bytes

func (v BlockHeader) Bytes() HeaderBytes

Bytes 转换位区块数据

func (BlockHeader) Check

func (v BlockHeader) Check() error

Check 取测区块头是否正确

func (*BlockHeader) Decode

func (v *BlockHeader) Decode(r IReader) error

Decode 解码数据

func (*BlockHeader) Encode

func (v *BlockHeader) Encode(w IWriter) error

Encode 编码数据

func (*BlockHeader) ID

func (v *BlockHeader) ID() (HASH256, error)

ID 计算ID

func (BlockHeader) IsGenesis

func (v BlockHeader) IsGenesis() bool

IsGenesis 是否是第一个区块

func (*BlockHeader) MustID

func (v *BlockHeader) MustID() HASH256

MustID 获取区块ID

func (*BlockHeader) ResetID

func (v *BlockHeader) ResetID() (HASH256, error)

ResetID 重置并结算ID

func (BlockHeader) String

func (v BlockHeader) String() string

type BlockIndex

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

BlockIndex 区块链结构

func GetBlockIndex

func GetBlockIndex() *BlockIndex

GetBlockIndex 获取全局主链

func InitBlockIndex

func InitBlockIndex(lis IListener) *BlockIndex

InitBlockIndex 初始化主链

func NewBlockIndex

func NewBlockIndex(lis IListener) *BlockIndex

NewBlockIndex 创建区块链

func NewTestBlockIndex

func NewTestBlockIndex(num int) *BlockIndex

NewTestBlockIndex 创建一个测试用区块索引 num创建num个区块

func (*BlockIndex) BestHeight

func (bi *BlockIndex) BestHeight() uint32

BestHeight 保存的最新区块高度

func (*BlockIndex) CacheSize

func (bi *BlockIndex) CacheSize() int

CacheSize 获取缓存大小

func (*BlockIndex) CalcBits

func (bi *BlockIndex) CalcBits(height uint32) uint32

CalcBits 计算当前区块高度对应的难度

func (*BlockIndex) Close

func (bi *BlockIndex) Close()

Close 关闭链数据

func (*BlockIndex) First

func (bi *BlockIndex) First() *TBEle

First 最低块

func (*BlockIndex) GetBestValue

func (bi *BlockIndex) GetBestValue() BestValue

GetBestValue 获取最高块信息

func (*BlockIndex) GetBlockConfirm

func (bi *BlockIndex) GetBlockConfirm(id HASH256) int

GetBlockConfirm 获取区块的确认数

func (*BlockIndex) GetBlockHeader

func (bi *BlockIndex) GetBlockHeader(id HASH256) (*TBEle, error)

GetBlockHeader 获取块头

func (*BlockIndex) GetCoin

func (bi *BlockIndex) GetCoin(pkh HASH160, txid HASH256, idx VarUInt) (*CoinKeyValue, error)

GetCoin 获取一笔金额

func (*BlockIndex) GetCoinWithAddress

func (bi *BlockIndex) GetCoinWithAddress(addr Address, txid HASH256, idx VarUInt) (*CoinKeyValue, error)

GetCoinWithAddress 从指定地址交易idx和输出索引获取金额信息

func (*BlockIndex) GetEle

func (bi *BlockIndex) GetEle(id HASH256) (*TBEle, error)

GetEle 获取区块头元素

func (*BlockIndex) GetMsgBlock

func (bi *BlockIndex) GetMsgBlock(id HASH256) (*MsgBlock, error)

GetMsgBlock 获取区块数据返回

func (*BlockIndex) GetMsgGetInv

func (bi *BlockIndex) GetMsgGetInv(msg *MsgGetInv, c *Client)

GetMsgGetInv 获取参数发送相关数据

func (*BlockIndex) GetTxConfirm

func (bi *BlockIndex) GetTxConfirm(id HASH256) int

GetTxConfirm 获取交易确认数(所属区块的确认数)

func (*BlockIndex) GetTxPool

func (bi *BlockIndex) GetTxPool() *TxPool

GetTxPool 获取内存交易池

func (*BlockIndex) HasBlock

func (bi *BlockIndex) HasBlock(id HASH256) (uint32, bool)

HasBlock 是否存在存在返回高度

func (*BlockIndex) HasSync

func (bi *BlockIndex) HasSync() bool

HasSync 是否有需要下载的区块

func (*BlockIndex) HasTxValue

func (bi *BlockIndex) HasTxValue(id HASH256) (bool, error)

HasTxValue 是否存在交易

func (*BlockIndex) Height

func (bi *BlockIndex) Height() uint32

Height 获取当前链高度

func (*BlockIndex) Last

func (bi *BlockIndex) Last() *TBEle

Last 最高块

func (*BlockIndex) LastHeaders

func (bi *BlockIndex) LastHeaders(limit int) Headers

LastHeaders 获取最后的多少个区块头

func (*BlockIndex) Len

func (bi *BlockIndex) Len() int

Len 链长度

func (*BlockIndex) LinkBack

func (bi *BlockIndex) LinkBack(e *TBEle)

LinkBack 连接区块头

func (*BlockIndex) LinkBlk

func (bi *BlockIndex) LinkBlk(blk *BlockInfo) error

LinkBlk 更新区块数据(需要区块头先链接好

func (*BlockIndex) ListCoins

func (bi *BlockIndex) ListCoins(addr Address) (*CoinsState, error)

ListCoins 获取某个地址账号的金额

func (*BlockIndex) ListCoinsWithAccount

func (bi *BlockIndex) ListCoinsWithAccount(acc *Account) (*CoinsState, error)

ListCoinsWithAccount 根据账号获取金额

func (*BlockIndex) ListCoinsWithCB

func (bi *BlockIndex) ListCoinsWithCB(addr Address, cb func(ckv *CoinKeyValue) bool) error

cb返回false,不再继续获取

func (*BlockIndex) ListCoinsWithID

func (bi *BlockIndex) ListCoinsWithID(pkh HASH160) (Coins, error)

ListCoinsWithID 获取某个id的所有余额 已经消费在内存中的不列出

func (*BlockIndex) ListTxs

func (bi *BlockIndex) ListTxs(addr Address, limit ...int) (TxIndexs, error)

ListTxs 获取某个地址相关的交易

func (*BlockIndex) ListTxsWithID

func (bi *BlockIndex) ListTxsWithID(id HASH160, limit ...int) (TxIndexs, error)

ListTxsWithID 获取交易

func (*BlockIndex) LoadAll

func (bi *BlockIndex) LoadAll(limit int, fn func(pv uint)) error

LoadAll 加载所有链meta f进度回调 0-100

func (*BlockIndex) LoadBlock

func (bi *BlockIndex) LoadBlock(id HASH256) (*BlockInfo, error)

LoadBlock 加载区块

func (*BlockIndex) LoadBlockWithH

func (bi *BlockIndex) LoadBlockWithH(h int) (*BlockInfo, error)

LoadWithHeight 按高度查询区块

func (*BlockIndex) LoadPrev

func (bi *BlockIndex) LoadPrev() (*TBEle, error)

LoadPrev 向前加载一个区块数据头

func (*BlockIndex) LoadTX

func (bi *BlockIndex) LoadTX(id HASH256) (*TX, error)

LoadTX 从链中获取一个交易

func (*BlockIndex) LoadTxValue

func (bi *BlockIndex) LoadTxValue(id HASH256) (*TxValue, error)

LoadTxValue 获取交易所在的区块和位置

func (*BlockIndex) NewBlock

func (bi *BlockIndex) NewBlock(ver uint32) (*BlockInfo, error)

NewBlock 创建下一个高度基本数据

func (*BlockIndex) NewIter

func (bi *BlockIndex) NewIter() *BIndexIter

NewIter 创建一个区块链迭代器

func (*BlockIndex) NewMsgGetBlock

func (bi *BlockIndex) NewMsgGetBlock(id HASH256) MsgIO

NewMsgGetBlock 创建区块网络消息

func (*BlockIndex) NewMsgHeaders

func (bi *BlockIndex) NewMsgHeaders(msg *MsgGetBlock) *MsgHeaders

NewMsgHeaders 创建证据区块头信息 默认获取30个区块头,如果分叉超过30个区块需要另外处理

func (*BlockIndex) NewMsgTxMerkle

func (bi *BlockIndex) NewMsgTxMerkle(id HASH256) (*MsgTxMerkle, error)

NewMsgTxMerkle 返回某个交易的merkle验证树

func (*BlockIndex) NewMsgVersion

func (bi *BlockIndex) NewMsgVersion() *MsgVersion

NewMsgVersion 在链上生成一个版本数据包

func (*BlockIndex) NewTrans

func (bi *BlockIndex) NewTrans(lis ITransListener) *Trans

NewTrans 创建待回调的交易对象

func (*BlockIndex) NextHeight

func (bi *BlockIndex) NextHeight() uint32

NextHeight 下一个块高度

func (*BlockIndex) ReadBlock

func (bi *BlockIndex) ReadBlock(id HASH256) ([]byte, error)

ReadBlock 读取区块数据

func (*BlockIndex) RemoveBestValue

func (bi *BlockIndex) RemoveBestValue() error

RemoveBestValue 移除数据库中的最新区块信息

func (*BlockIndex) Time

func (bi *BlockIndex) Time() uint32

Time 获取当前链最高区块时间,空链获取当前时间

func (bi *BlockIndex) Unlink(hds Headers) error

Unlink 根据证据区块链修正本地链,回退到一个指定id重新链接

func (*BlockIndex) UnlinkCount

func (bi *BlockIndex) UnlinkCount(id HASH256) (uint32, error)

UnlinkCount 返回需要断开的区块数量

func (*BlockIndex) UnlinkLast

func (bi *BlockIndex) UnlinkLast() error

UnlinkLast 断开最后一个区块

func (*BlockIndex) UnlinkTo

func (bi *BlockIndex) UnlinkTo(id HASH256) error

UnlinkTo 必须从最后开始断开,回退到指定id,不包括id

func (*BlockIndex) WriteGenesis

func (bi *BlockIndex) WriteGenesis()

WriteGenesis 加载写入第一个区块

type BlockInfo

type BlockInfo struct {
	Header BlockHeader //区块头
	Txs    []*TX       //交易记录,类似比特币
	Meta   *TBEle      //指向链节点
	// contains filtered or unexported fields
}

BlockInfo txs交易部分和比特币类似 块大小限制为4M大小

func (*BlockInfo) AddTxs

func (blk *BlockInfo) AddTxs(bi *BlockIndex, txs []*TX) error

AddTxs 添加多个交易 有重复消费输出将会失败

func (*BlockInfo) Check

func (blk *BlockInfo) Check(bi *BlockIndex, csp bool) error

Check 检查区块数据 csp 是否检查消费输出

func (*BlockInfo) CheckCoinbase

func (blk *BlockInfo) CheckCoinbase() error

CheckCoinbase 检测coinbas

func (*BlockInfo) CheckRefsTx

func (blk *BlockInfo) CheckRefsTx(bi *BlockIndex, tx *TX) error

CheckRefsTx 检查引用的tx是否存在区块中

func (*BlockInfo) CheckRepCostTxOut

func (blk *BlockInfo) CheckRepCostTxOut(bi *BlockIndex) error

CheckRepCostTxOut 检查是否有多个输入消费同一个输出

func (*BlockInfo) CheckTxs

func (blk *BlockInfo) CheckTxs(bi *BlockIndex, csp bool) error

CheckTxs 检查所有的交易 csp 是否检查消费金额是否存在,只有消费此输出得时候才检查,如果对应 的区块已经连接到主链,输出必定被消费了,只需要检查签名

func (*BlockInfo) CoinbaseFee

func (blk *BlockInfo) CoinbaseFee() (Amount, error)

CoinbaseFee 获取coinse out fee sum

func (*BlockInfo) CoinbaseReward

func (blk *BlockInfo) CoinbaseReward() Amount

CoinbaseReward 获取区块奖励

func (*BlockInfo) CoinbaseScript

func (blk *BlockInfo) CoinbaseScript(ip []byte, bs ...[]byte) (Script, error)

CoinbaseScript 创建Cosinbase 脚本

func (*BlockInfo) Decode

func (blk *BlockInfo) Decode(r IReader) error

Decode 解码区块数据

func (*BlockInfo) EachOutScript

func (blk *BlockInfo) EachOutScript(fn func(tx *TX, idx int, script *LockedScript))

遍历区块中输出脚本

func (*BlockInfo) Encode

func (blk *BlockInfo) Encode(w IWriter) error

Encode 编码区块数据

func (*BlockInfo) EndianHeight

func (blk *BlockInfo) EndianHeight() []byte

EndianHeight 获取区块高度的二进制

func (BlockInfo) ExecScript

func (blk BlockInfo) ExecScript(bi *BlockIndex) error

ExecScript 执行脚本检测

func (*BlockInfo) Finish

func (blk *BlockInfo) Finish(bi *BlockIndex) error

Finish 完成块数据

func (*BlockInfo) GetFee

func (blk *BlockInfo) GetFee(bi *BlockIndex) (Amount, error)

GetFee 获取总的交易费

func (*BlockInfo) GetIncome

func (blk *BlockInfo) GetIncome(bi *BlockIndex) (Amount, error)

GetIncome 获取区块收益

func (*BlockInfo) GetMerkle

func (blk *BlockInfo) GetMerkle() (HASH256, error)

GetMerkle 获取默克尔树

func (*BlockInfo) GetTx

func (blk *BlockInfo) GetTx(idx int) (*TX, error)

GetTx 获取区块交易

func (*BlockInfo) HasTx

func (blk *BlockInfo) HasTx(id HASH256) bool

HasTx 查找区块内的单个交易是否存在

func (*BlockInfo) ID

func (blk *BlockInfo) ID() (HASH256, error)

ID 获取区块id

func (*BlockInfo) IsGenesis

func (blk *BlockInfo) IsGenesis() bool

IsGenesis 是否是第一个区块

func (*BlockInfo) LoadTxs

func (blk *BlockInfo) LoadTxs(bi *BlockIndex) error

LoadTxs 从交易池加载可用的交易

func (*BlockInfo) MustID

func (blk *BlockInfo) MustID() HASH256

MustID 获取区块id

func (*BlockInfo) ResetHasher

func (blk *BlockInfo) ResetHasher()

ResetHasher 重置所有hash缓存

func (*BlockInfo) SetMerkle

func (blk *BlockInfo) SetMerkle() error

SetMerkle 结算并设置默克尔树

func (BlockInfo) String

func (blk BlockInfo) String() string

func (*BlockInfo) Verify

func (blk *BlockInfo) Verify(ele *TBEle, bi *BlockIndex) error

Verify 验证区块数据

func (*BlockInfo) Write

func (blk *BlockInfo) Write(bi *BlockIndex) error

func (*BlockInfo) WriteTxsIdx

func (blk *BlockInfo) WriteTxsIdx(bi *BlockIndex, bt *Batch) error

WriteTxsIdx 写入交易索引

type BloomFilter

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

BloomFilter 布隆过滤器

func NewBloomFilter

func NewBloomFilter(funcs uint32, tweak uint32, filter []byte) (*BloomFilter, error)

NewBloomFilter 创建指定参数的布隆过滤器

func (*BloomFilter) Add

func (b *BloomFilter) Add(key []byte)

Add 添加一个数据到过滤器

func (*BloomFilter) GetFilter

func (b *BloomFilter) GetFilter() []byte

GetFilter 获取过滤器数据

func (*BloomFilter) Has

func (b *BloomFilter) Has(key []byte) bool

Has 检测是否存在指定的key数据

func (*BloomFilter) Hash

func (b *BloomFilter) Hash(n int, key []byte) uint32

Hash 计算hash

func (*BloomFilter) NewMsgFilterLoad

func (b *BloomFilter) NewMsgFilterLoad() *MsgFilterLoad

NewMsgFilterLoad 获取一个过滤器加载消息

func (*BloomFilter) SetFilter

func (b *BloomFilter) SetFilter(filter []byte)

SetFilter 设置过滤数据

type Cache

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

Cache 缓存器

func NewCache

func NewCache(defaultExpiration, cleanupInterval time.Duration) *Cache

NewCache Return a new cache with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

func NewCacheFrom

func NewCacheFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache

NewCacheFrom Return a new cache with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

NewFrom() also accepts an items map which will serve as the underlying map for the cache. This is useful for starting from a deserialized cache (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. make(map[string]Item, 500) to improve startup performance when the cache is expected to reach a certain minimum size.

Only the cache's methods synchronize access to this map, so it is not recommended to keep any references to the map around after creating a cache. If need be, the map can be accessed at a later point using c.Items() (subject to the same caveat.)

Note regarding serialization: When using e.g. gob, make sure to gob.Register() the individual types stored in the cache before encoding a map retrieved with c.Items(), and to register those same types before decoding a blob containing an items map.

func (*Cache) Add

func (c *Cache) Add(k string, x interface{}, d time.Duration) error

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise.

func (*Cache) Decrement

func (c *Cache) Decrement(k string, n int64) error

Decrement an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to decrement it by n. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementInt64.

func (*Cache) DecrementFloat

func (c *Cache) DecrementFloat(k string, n float64) error

DecrementFloat an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to decrement it by n. Pass a negative number to decrement the value. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementFloat64.

func (*Cache) DecrementFloat32

func (c *Cache) DecrementFloat32(k string, n float32) (float32, error)

DecrementFloat32 an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementFloat64

func (c *Cache) DecrementFloat64(k string, n float64) (float64, error)

DecrementFloat64 an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementInt

func (c *Cache) DecrementInt(k string, n int) (int, error)

DecrementInt an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementInt16

func (c *Cache) DecrementInt16(k string, n int16) (int16, error)

DecrementInt16 an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementInt32

func (c *Cache) DecrementInt32(k string, n int32) (int32, error)

DecrementInt32 an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementInt64

func (c *Cache) DecrementInt64(k string, n int64) (int64, error)

DecrementInt64 an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementInt8

func (c *Cache) DecrementInt8(k string, n int8) (int8, error)

DecrementInt8 an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementUint

func (c *Cache) DecrementUint(k string, n uint) (uint, error)

DecrementUint an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementUint16

func (c *Cache) DecrementUint16(k string, n uint16) (uint16, error)

DecrementUint16 an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementUint32

func (c *Cache) DecrementUint32(k string, n uint32) (uint32, error)

DecrementUint32 an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementUint64

func (c *Cache) DecrementUint64(k string, n uint64) (uint64, error)

DecrementUint64 an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementUint8

func (c *Cache) DecrementUint8(k string, n uint8) (uint8, error)

DecrementUint8 an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) DecrementUintptr

func (c *Cache) DecrementUintptr(k string, n uintptr) (uintptr, error)

DecrementUintptr an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the decremented value is returned.

func (*Cache) Delete

func (c *Cache) Delete(k string)

Delete an item from the cache. Does nothing if the key is not in the cache.

func (*Cache) DeleteExpired

func (c *Cache) DeleteExpired()

DeleteExpired all expired items from the cache.

func (*Cache) Flush

func (c *Cache) Flush()

Flush Delete all items from the cache.

func (*Cache) Get

func (c *Cache) Get(k string) (interface{}, bool)

Get an item from the cache. Returns the item or nil, and a bool indicating whether the key was found.

func (*Cache) GetWithExpiration

func (c *Cache) GetWithExpiration(k string) (interface{}, time.Time, bool)

GetWithExpiration returns an item and its expiration time from the cache. It returns the item or nil, the expiration time if one is set (if the item never expires a zero value for time.Time is returned), and a bool indicating whether the key was found.

func (*Cache) Increment

func (c *Cache) Increment(k string, n int64) error

Increment an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to increment it by n. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementInt64.

func (*Cache) IncrementFloat

func (c *Cache) IncrementFloat(k string, n float64) error

IncrementFloat an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to increment it by n. Pass a negative number to decrement the value. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementFloat64.

func (*Cache) IncrementFloat32

func (c *Cache) IncrementFloat32(k string, n float32) (float32, error)

IncrementFloat32 an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementFloat64

func (c *Cache) IncrementFloat64(k string, n float64) (float64, error)

IncrementFloat64 an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementInt

func (c *Cache) IncrementInt(k string, n int) (int, error)

IncrementInt an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementInt16

func (c *Cache) IncrementInt16(k string, n int16) (int16, error)

IncrementInt16 an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementInt32

func (c *Cache) IncrementInt32(k string, n int32) (int32, error)

IncrementInt32 an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementInt64

func (c *Cache) IncrementInt64(k string, n int64) (int64, error)

IncrementInt64 an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementInt8

func (c *Cache) IncrementInt8(k string, n int8) (int8, error)

IncrementInt8 an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementUint

func (c *Cache) IncrementUint(k string, n uint) (uint, error)

IncrementUint an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementUint16

func (c *Cache) IncrementUint16(k string, n uint16) (uint16, error)

IncrementUint16 an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementUint32

func (c *Cache) IncrementUint32(k string, n uint32) (uint32, error)

IncrementUint32 an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementUint64

func (c *Cache) IncrementUint64(k string, n uint64) (uint64, error)

IncrementUint64 an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementUint8

func (c *Cache) IncrementUint8(k string, n uint8) (uint8, error)

IncrementUint8 an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) IncrementUintptr

func (c *Cache) IncrementUintptr(k string, n uintptr) (uintptr, error)

IncrementUintptr an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the incremented value is returned.

func (*Cache) ItemCount

func (c *Cache) ItemCount() int

ItemCount Returns the number of items in the cache. This may include items that have expired, but have not yet been cleaned up.

func (*Cache) Items

func (c *Cache) Items() map[string]Item

Items , Copies all unexpired items in the cache into a new map and returns it.

func (*Cache) Load

func (c *Cache) Load(r io.Reader) error

Load . Add (Gob-serialized) cache items from an io.Reader, excluding any items with keys that already exist (and haven't expired) in the current cache.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Cache) LoadFile

func (c *Cache) LoadFile(fname string) error

LoadFile , Load and add cache items from the given filename, excluding any items with keys that already exist in the current cache.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Cache) OnEvicted

func (c *Cache) OnEvicted(f func(string, interface{}))

OnEvicted Sets an (optional) function that is called with the key and value when an item is evicted from the cache. (Including when it is deleted manually, but not when it is overwritten.) Set to nil to disable.

func (*Cache) Replace

func (c *Cache) Replace(k string, x interface{}, d time.Duration) error

Replace Set a new value for the cache key only if it already exists, and the existing item hasn't expired. Returns an error otherwise.

func (*Cache) Save

func (c *Cache) Save(w io.Writer) (err error)

Save , Write the cache's items (using Gob) to an io.Writer.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Cache) SaveFile

func (c *Cache) SaveFile(fname string) error

SaveFile the cache's items to the given filename, creating the file if it doesn't exist, and overwriting it if it does.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Cache) Set

func (c *Cache) Set(k string, x interface{}, d time.Duration)

Set Add an item to the cache, replacing any existing item. If the duration is 0 (DefaultExpiration), the cache's default expiration time is used. If it is -1 (NoExpiration), the item never expires.

func (*Cache) SetDefault

func (c *Cache) SetDefault(k string, x interface{})

SetDefault Add, an item to the cache, replacing any existing item, using the default expiration.

type Client

type Client struct {
	*NetStream

	Addr NetAddr

	Ver     uint32 //节点版本
	Service uint32 //节点提供的服务
	Height  uint32 //节点区块高度
	// contains filtered or unexported fields
}

Client 连接客户端类型定义

func (*Client) Close

func (c *Client) Close()

Close 关闭客户端

func (*Client) Equal

func (c *Client) Equal(b *Client) bool

Equal 是否是相同的客户端 检测节点id是否一致

func (*Client) FilterAdd

func (c *Client) FilterAdd(key []byte) error

FilterAdd 添加过滤数据

func (*Client) FilterClear

func (c *Client) FilterClear()

FilterClear 清除过滤器

func (*Client) FilterHas

func (c *Client) FilterHas(key []byte) bool

FilterHas 检测过滤器是否存在

func (*Client) GetFilter

func (c *Client) GetFilter() (*BloomFilter, bool)

GetFilter 获取连接上的过滤器 不存在返回nil,false

func (*Client) ID

func (c *Client) ID() uint64

func (*Client) IsIn

func (c *Client) IsIn() bool

IsIn 是否是连入的

func (*Client) IsOut

func (c *Client) IsOut() bool

IsOut 是否是连出的

func (*Client) LoadFilter

func (c *Client) LoadFilter(funcs uint32, tweak uint32, filter []byte) error

LoadFilter 设置过滤器

func (*Client) Loop

func (c *Client) Loop()

Loop 开始后台启动服务

func (*Client) Open

func (c *Client) Open(addr NetAddr) error

Open 连接到指定地址

func (*Client) SendMsg

func (c *Client) SendMsg(m MsgIO)

SendMsg 发送消息

type ClientMsg

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

ClientMsg 是网络消息通道数据类型

func NewClientMsg

func NewClientMsg(c *Client, m MsgIO) *ClientMsg

NewClientMsg 会创建一个新的网络通道数据

func (*ClientMsg) GetClient

func (msg *ClientMsg) GetClient() *Client

func (*ClientMsg) GetMsg

func (msg *ClientMsg) GetMsg() MsgIO

type CoinKeyValue

type CoinKeyValue struct {
	CPkh   HASH160 //公钥hash
	TxID   HASH256 //交易id
	Index  VarUInt //输出索引
	Value  Amount  //输出金额
	Base   uint8   //是否属于coinbase o or 1
	Height VarUInt //所在区块高度
	// contains filtered or unexported fields
}

CoinKeyValue 金额存储结构

func (*CoinKeyValue) From

func (tk *CoinKeyValue) From(k []byte, v []byte) error

From 从kv获取数据

func (CoinKeyValue) GetAddress

func (tk CoinKeyValue) GetAddress() Address

GetAddress 获取金额所在地址

func (CoinKeyValue) ID

func (tk CoinKeyValue) ID() string

ID 获取金额唯一ID

func (CoinKeyValue) IsMatured

func (tk CoinKeyValue) IsMatured(spent uint32) bool

IsMatured 是否成熟可用

func (CoinKeyValue) IsPool

func (tk CoinKeyValue) IsPool() bool

IsPool 是否来自交易池

func (CoinKeyValue) MustKey

func (tk CoinKeyValue) MustKey() []byte

MustKey 用来存储pkh拥有的可消费的金额

func (CoinKeyValue) MustValue

func (tk CoinKeyValue) MustValue() []byte

MustValue 必定获取二进制

func (CoinKeyValue) NewTxIn

func (tk CoinKeyValue) NewTxIn(wits *WitnessScript) (*TxIn, error)

NewTxIn 创建一个消费输入

func (CoinKeyValue) SpentKey

func (tk CoinKeyValue) SpentKey() []byte

SpentKey 消费key,用来记录输入对应的输出是否已经被消费

type Coins

type Coins []*CoinKeyValue

Coins 金额记录

func (Coins) Balance

func (c Coins) Balance() Amount

Balance 获取总金额

func (Coins) Find

func (c Coins) Find(fn func(cp *CoinKeyValue) bool) Coins

Find 根据回调获取金额 回调返回true加入返回列表

func (Coins) FindCoin

func (c Coins) FindCoin(id string) (*CoinKeyValue, error)

FindCoin 根据Id搜索金额

func (Coins) Sort

func (c Coins) Sort() Coins

Sort 按高度升序排序

func (Coins) State

func (c Coins) State(spent uint32) *CoinsState

State 假设当前消费高度为 spent 获取金额状态

type CoinsState

type CoinsState struct {
	Locks Coins //锁定的
	Coins Coins //当前可用
	All   Coins //所有
}

CoinsState 金额状态

func (*CoinsState) Merge

func (s *CoinsState) Merge(v *CoinsState)

Merge 拼合

func (CoinsState) String

func (s CoinsState) String() string

type Config

type Config struct {
	Name      string   `json:"name"`      //配置文件名称
	Confirms  uint32   `json:"confirms"`  //安全确认数 = 6
	MinerNum  int      `json:"miner_num"` //挖掘机数量,=0不会启动协程挖矿
	MaxConn   int      `json:"max_conn"`  //最大激活的连接,包括连入和连出的
	Seeds     []string `json:"seeds"`     //dns seed服务器
	DataDir   string   `json:"data_dir"`  //数据路径
	Genesis   string   `json:"genesis"`   //第一个区块
	LogFile   string   `json:"log_file"`  //日志文件路径
	PowTime   uint     `json:"pow_time"`  //14 * 24 * 60 * 60=1209600
	PowLimit  string   `json:"pow_limit"` //最小难度设置
	PowSpan   uint32   `json:"pow_span"`  //难度计算间隔 2016
	Halving   int      `json:"halving"`   //210000减产配置
	Ver       uint32   `json:"version"`   //节点版本
	TCPPort   int      `json:"tcp_port"`  //服务端口和ip
	TCPIp     string   `json:"tcp_ip"`    //节点远程连接ip
	LimitHash UINT256  `json:"-"`         //最小工作难度
	Nodes     []string `json:"nodes"`     //配置的可用节点
	// contains filtered or unexported fields
}

Config 配置加载后只读

func GetConfig

func GetConfig() *Config

GetConfig 获取当前配置

func InitConfig

func InitConfig(file ...string) *Config

InitConfig 初始化配置

func LoadConfig

func LoadConfig(f string) *Config

LoadConfig 加载配置

func NewTestConfig

func NewTestConfig(dir ...string) *Config

NewTestConfig 创建一个测试用的配置

func (*Config) Close

func (c *Config) Close()

Close 关闭

func (*Config) GenUInt64

func (c *Config) GenUInt64() uint64

GenUInt64 创建64位随机值

func (*Config) GetLogFile

func (c *Config) GetLogFile() *os.File

GetLogFile 获取日志文件

func (*Config) GetNetAddr

func (c *Config) GetNetAddr() NetAddr

GetNetAddr 获取网络地址

func (*Config) GetTCPListenAddr

func (c *Config) GetTCPListenAddr() NetAddr

GetTCPListenAddr 获取服务地址

func (*Config) Init

func (c *Config) Init() *Config

Init 初始化

func (*Config) IsGenesisID

func (c *Config) IsGenesisID(id HASH256) bool

IsGenesisID 检测id是否是第一个区块

type CtrlPrivateKeyReq

type CtrlPrivateKeyReq struct {
	ID      string //私钥ID
	RandStr string //给定一个随机字符串
}

CtrlPrivateKeyReq 私钥控制权证明请求参数

type CtrlPrivateKeyRes

type CtrlPrivateKeyRes struct {
	RandStr string   //给定的随机字符串
	Pks     PKBytes  //返回私钥对应的公钥
	Sig     SigBytes //随机字符串签名
}

CtrlPrivateKeyRes 私钥控制权结果

func (CtrlPrivateKeyRes) Check

func (res CtrlPrivateKeyRes) Check(req *CtrlPrivateKeyReq) error

检测是否签名正确

type DBImp

type DBImp interface {
	Has(ks ...[]byte) (bool, error)     //key是否存在
	Put(ks ...[]byte) error             //添加键值
	Get(ks ...[]byte) ([]byte, error)   //根据key获取值
	Del(ks ...[]byte) error             //删除key
	Write(b *Batch, sync ...bool) error //批量写
	Compact(r *Range) error             //合并
	Close()                             //关闭数据库
	Iterator(slice ...*Range) *Iterator //搜索
	Sync()                              //同步到磁盘
	SizeOf(r []*Range) ([]int64, error) //获取范围内数量
	Transaction() (TRImp, error)        //创建事务
	NewBatch() *Batch                   //创建批量
	LoadBatch(d []byte) (*Batch, error) //加载批量数据
}

DBImp 数据基本操作接口

func NewDB

func NewDB(dbp *leveldb.DB) DBImp

NewDB 创建基于leveldb的数据库接口

func NewDBImp

func NewDBImp(dir string, opts ...*opt.Options) (DBImp, error)

NewDBImp 创建数据库接口

type Document

type Document struct {
	ID    DocumentID //文档ID
	Tags  []string   //标签
	TxID  HASH256    //文档对应交易ID
	Index VarUInt    //文档对应的输出索引
	Body  VarBytes   //内容
	Next  DocumentID //下个关系
	Prev  DocumentID //上个关系
}

Document 文档关键字查询存储系统 next prev为存在链式关系时启用

func NewDocument

func NewDocument() *Document

func (*Document) Decode

func (doc *Document) Decode(b []byte)

func (Document) Encode

func (doc Document) Encode() []byte

func (*Document) GetNext

func (doc *Document) GetNext(db IDocSystem, qtag ...bool) (*Document, error)

func (*Document) GetPrev

func (doc *Document) GetPrev(db IDocSystem, qtag ...bool) (*Document, error)

type DocumentID

type DocumentID [12]byte

第一个字节为分类字节,可分0-254类

var NilDocumentID DocumentID

func DocumentIDFromHex

func DocumentIDFromHex(s string) DocumentID

func NewDocumentID

func NewDocumentID(typ ...byte) DocumentID

func NewDocumentIDFrom

func NewDocumentIDFrom(b []byte) DocumentID

func NewDocumentIDFromTimestamp

func NewDocumentIDFromTimestamp(typ byte, timestamp time.Time) DocumentID

func (*DocumentID) Decode

func (id *DocumentID) Decode(r IReader) error

func (DocumentID) Encode

func (id DocumentID) Encode(w IWriter) error

func (DocumentID) Equal

func (id DocumentID) Equal(v DocumentID) bool

func (DocumentID) IsNil

func (id DocumentID) IsNil() bool

是否是空的id

func (DocumentID) MarshalJSON

func (id DocumentID) MarshalJSON() ([]byte, error)

func (*DocumentID) SetType

func (id *DocumentID) SetType(typ byte)

修改类型字节

func (DocumentID) String

func (id DocumentID) String() string

func (DocumentID) To

func (id DocumentID) To(typ byte) DocumentID

复制id并转换到指定类型

func (DocumentID) Type

func (id DocumentID) Type() byte

获取类型字节

func (*DocumentID) UnmarshalJSON

func (id *DocumentID) UnmarshalJSON(b []byte) error

type FLocker

type FLocker interface {
	Lock() error
	Release() error
}

FLocker 文件锁多平台实现

func NewFLocker

func NewFLocker(path string, readOnly bool) FLocker

type HASH160

type HASH160 [20]byte

HASH160 公钥HASH160

func DecodeAddress

func DecodeAddress(addr Address) (HASH160, error)

DecodeAddress 解码地址

func DecodeAddressWithPrefix

func DecodeAddressWithPrefix(addr string) (string, HASH160, error)

DecodeAddressWithPrefix 编码地址用指定前缀

func Hash160From

func Hash160From(b []byte) HASH160

Hash160From 返回hash160值

func HashPkh

func HashPkh(num uint8, less uint8, arb uint8, pkhs []HASH256) (HASH160, error)

HashPkh hash公钥。地址hash也将由这个方法生成 生成地址使用公钥hash256,不公开公钥生成收款地址可使用此方法

func HashPks

func HashPks(num uint8, less uint8, arb uint8, pks []PKBytes) (HASH160, error)

HashPks hash公钥。地址hash也将由这个方法生成

func NewHASH160

func NewHASH160(v interface{}) HASH160

NewHASH160 初始化hash160

func (HASH160) Bytes

func (v HASH160) Bytes() []byte

Bytes 返回二进制数据

func (HASH160) Cmp

func (v HASH160) Cmp(b HASH160) int

Cmp 转换位hash256比较大小

func (*HASH160) Decode

func (v *HASH160) Decode(r IReader) error

Decode 从读缓存解码

func (HASH160) Encode

func (v HASH160) Encode(w IWriter) error

Encode 编码到写缓存

func (HASH160) Equal

func (v HASH160) Equal(b HASH160) bool

Equal 是否相等

func (*HASH160) Set

func (v *HASH160) Set(b []byte)

Set 二进制初始化

func (*HASH160) SetPK

func (v *HASH160) SetPK(pk *PublicKey)

SetPK 使用公钥初始化

func (HASH160) String

func (v HASH160) String() string

type HASH256

type HASH256 [32]byte

HASH256 bit256 hash

func DecodePublicHash

func DecodePublicHash(addr string) (HASH256, error)

DecodePublicHash 解码公钥hash

func Hash256From

func Hash256From(b []byte) HASH256

Hash256From 返回hash256值

func NewHASH256

func NewHASH256(v interface{}) HASH256

NewHASH256 动态类型创建

func (HASH256) Bytes

func (h HASH256) Bytes() []byte

Bytes 获取二进制数据

func (HASH256) Clone

func (h HASH256) Clone() HASH256

Clone 复制

func (*HASH256) Decode

func (h *HASH256) Decode(r IReader) error

Decode decode

func (HASH256) Encode

func (h HASH256) Encode(w IWriter) error

Encode encode

func (HASH256) Equal

func (h HASH256) Equal(v HASH256) bool

Equal ==

func (HASH256) EqualBytes

func (h HASH256) EqualBytes(b []byte) bool

EqualBytes 余字节二进制对比

func (HASH256) GetUint64

func (h HASH256) GetUint64(idx int) uint64

GetUint64 获取64位值

func (HASH256) IsZero

func (h HASH256) IsZero() bool

IsZero 是否为空

func (*HASH256) Set

func (h *HASH256) Set(b []byte)

Set 二进制初始化

func (HASH256) String

func (h HASH256) String() string

func (HASH256) Swap

func (h HASH256) Swap() HASH256

Swap 反转

func (HASH256) ToU256

func (h HASH256) ToU256() UINT256

ToU256 hash256转为大数

type HashCacher

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

HashCacher hash 缓存

func (*HashCacher) Hash

func (h *HashCacher) Hash(b []byte) HASH256

Hash 计算hash

func (HashCacher) IsSet

func (h HashCacher) IsSet() (HASH256, bool)

IsSet 是否设置了hash

func (*HashCacher) Reset

func (h *HashCacher) Reset()

Reset 重置

func (*HashCacher) SetHash

func (h *HashCacher) SetHash(hv HASH256)

SetHash 设置hash

type HeaderBytes

type HeaderBytes []byte

HeaderBytes 区块头数据

func (HeaderBytes) Clone

func (b HeaderBytes) Clone() HeaderBytes

Clone 复制区块头

func (*HeaderBytes) Hash

func (b *HeaderBytes) Hash() HASH256

Hash 计算hash

func (*HeaderBytes) Header

func (b *HeaderBytes) Header() BlockHeader

Header 返回区块头

func (*HeaderBytes) SetNonce

func (b *HeaderBytes) SetNonce(v uint32)

SetNonce 设置随机值

func (*HeaderBytes) SetTime

func (b *HeaderBytes) SetTime(v uint32)

SetTime 设置时间戳

type Headers

type Headers []BlockHeader

Headers 区块头集合

func (*Headers) Add

func (hs *Headers) Add(h BlockHeader)

Add 添加区块头

func (Headers) Check

func (hs Headers) Check(height uint32, bi *BlockIndex) error

Check 检测区块头列表高度从height开始

func (*Headers) Decode

func (hs *Headers) Decode(r IReader) error

Decode 解码区块头集合

func (Headers) Encode

func (hs Headers) Encode(w IWriter) error

Encode 编码区块头集合

func (*Headers) Reverse

func (hs *Headers) Reverse()

Reverse 倒置区块头集合

type IBlkStore

type IBlkStore interface {
	//同步数据
	Sync()
	//关闭数据库
	Close()
	//初始化
	Init(arg ...interface{})
	//索引数据库
	Index() DBImp
	//区块数据文件
	Blk() IChunkStore
	//事物回退文件
	Rev() IChunkStore
}

IBlkStore 区块存储

func NewLevelDBStore

func NewLevelDBStore(dir string) IBlkStore

NewLevelDBStore 创建leveldb存储器

type IChunkStore

type IChunkStore interface {
	Read(st BlkChunk) ([]byte, error)
	Write(b []byte) (BlkChunk, error)
	Close()
	Init() error
	Sync(id ...uint32)
}

IChunkStore 数据块存储

type ICoder

type ICoder interface {
	Encode(bb []byte) ([]byte, error)
	Decode(bb []byte) ([]byte, error)
}

文档编码器

var (
	LzmaCoder ICoder = lzmacoder{}
)

type IDocIter

type IDocIter interface {
	//遍历文档
	Each(fn func(doc *Document) error) error
	//跳过文档
	Skip(skip int) IDocIter
	//限制数量
	Limit(limit int) IDocIter
	//是否查询包含的所有tags 有损一点性能
	Tags(v bool) IDocIter
	//ByNext 向下迭代
	ByNext() IDocIter
	//ByPrev 向上迭代
	ByPrev() IDocIter
	//获取最后一个key
	LastKey() []byte
	//设置lastkey
	SetLastKey(lk []byte)
}

type IDocSystem

type IDocSystem interface {
	//追加tag
	AddTag(id DocumentID, tags ...string) error
	//删除tag
	DelTag(id DocumentID, tags ...string) error
	//添加文档
	Insert(doc ...*Document) error
	//删除文档
	Delete(id ...DocumentID) error
	//更新文档
	Update(doc ...*Document) error
	//根据id获取文档内容 qtag是否查询tags
	Get(id DocumentID, qtag ...bool) (*Document, error)
	//文档是否存在
	Has(id DocumentID) (bool, error)
	//固定key查询
	Find(key string) IDocIter
	//获取所有文档 prefix存在时拼接前缀
	All(prefix ...[]byte) IDocIter
	//按前缀查询文档
	Prefix(key string) IDocIter
	//模糊查询文档使用正则
	Regex(str string) IDocIter
	//写入磁盘
	Sync()
	//关闭文件系统
	Close()
}

标签索引库接口

func OpenDocSystem

func OpenDocSystem(dir string) (IDocSystem, error)

OpenDocSystem 打开文档系统,不存在自动创建

type IGetSigBytes

type IGetSigBytes interface {
	GetSigBytes() ([]byte, error)
}

IGetSigBytes 获取签名数据接口

type IKeysDB

type IKeysDB interface {
	Sync()
	//关闭密钥数据库
	Close()
	//创建一个1-1账号返回描述信息
	NewAccountInfo(typ int, desc string) (*AccountInfo, error)
	//创建一个新的私钥
	NewPrivateKey() (string, error)
	//获取一个私钥
	LoadPrivateKey(id string) (*PrivateKey, error)
	//保存账户地址描述
	SaveAccountInfo(ka *AccountInfo) (Address, error)
	//加载账户地址描述
	LoadAccountInfo(id Address) (*AccountInfo, error)
	//是否有私钥控制权
	HasKeyPrivileges(req *CtrlPrivateKeyReq) (*CtrlPrivateKeyRes, error)
	//创建待签名脚本
	NewWitnessScript(id Address, execs ...[]byte) (*WitnessScript, error)
	//创建锁定脚本
	NewLockedScript(id Address, meta []byte, exec ...[]byte) (*LockedScript, error)
	//签名并填充脚本数据
	Sign(id Address, data []byte, wits *WitnessScript) error
	//签名指定的账户信息
	SignAccount(ka *AccountInfo, data []byte, wits *WitnessScript) error
	//删除私钥
	DeletePrivateKey(id string) error
	//删除账户描述
	DeleteAccountInfo(id Address) error
	//设置密钥ttl为过期时间
	SetKey(key string, ttl time.Duration)
	//列出地址
	ListAddress(limit int, skey ...[]byte) ([]Address, []byte)
	//列出私钥id
	ListPrivate(limit int, skey ...[]byte) ([]string, []byte)
	//添加配置
	PutConfig(id string, v []byte) error
	//获取配置
	GetConfig(id string) ([]byte, error)
	//是否存在配置
	HasConfig(id string) (bool, error)
	//RSA密钥存储
	NewRSA() (string, error)
	HasRSA(id string) (bool, error)
	ListRSA() []string
	GetRSA(id string) (*RSAPrivateKey, error)
}

func OpenKeysDB

func OpenKeysDB(dir string, key ...string) (IKeysDB, error)

type IListener

type IListener interface {
	//首次初始化时在加载区块链之前
	OnInit(bi *BlockIndex) error
	//时间戳发生器
	TimeNow() uint32
	//当一个区块断开后
	OnUnlinkBlock(blk *BlockInfo)
	//更新区块数据成功时
	OnLinkBlock(blk *BlockInfo)
	//当块创建时,可以添加,修改块内信息
	OnNewBlock(blk *BlockInfo) error
	//完成区块,当检测完成调用,设置merkle之前
	OnFinished(blk *BlockInfo) error
	//当加载交易列表到区块时可用此方法过滤不加入区块的
	//调用 AddTxs 时会触发
	OnLoadTxs(txs []*TX) []*TX
	//链关闭时
	OnClose()
	//当服务启动后会调用一次,区块链,节点服务启动后
	OnStart()
	//系统结束时
	OnStop()
	//当交易进入交易池之前,返回错误不会进入交易池
	OnTxPool(tx *TX) error
	//当交易池的交易被替换时
	OnTxPoolRep(old *TX, new *TX)
	//返回矿工账号,如果返回将优先使用这个地址
	MinerAddr() Address
}

IListener 所有回调可能来自不同的协程

type IMiner

type IMiner interface {
	//开始工作
	Start(ctx context.Context, lis IListener)
	//停止
	Stop()
	//等待停止
	Wait()
	//获取区块头
	GetHeader() ([]byte, error)
	//设置区块头
	SetHeader(b []byte) error
	//重新开始计算区块
	ResetMiner() error
	//当前时间戳
	TimeNow() uint32
	//发送创建新区块请求
	NewBlock(ver uint32)
}

IMiner 矿工接口

type IMsgMeta

type IMsgMeta interface {
	NewMeta() []byte
}

IMsgMeta 创建一个meta信息

type INetStream

type INetStream interface {
	ReadMsg() (MsgIO, error)
	WriteMsg(m MsgIO) error
	IReadWriter
	io.Closer
}

INetStream 网络流接口

type IReadWriter

type IReadWriter interface {
	IReader
	IWriter
}

IReadWriter 数据流读写接口

func NewReadWriter

func NewReadWriter() IReadWriter

NewReadWriter 使用二进制buf创建读写流

type IReader

type IReader interface {
	io.Reader
	io.ByteReader
	TRead(data interface{}) error
	ReadFull(dp []byte) error
}

IReader 数据流读接口

func NewReader

func NewReader(b []byte) IReader

NewReader 从二进制创建读取流

type ISerializable

type ISerializable interface {
	Encode(w IWriter) error
	Decode(r IReader) error
}

type IServer

type IServer interface {
	Start(ctx context.Context, lis IListener)
	Stop()
	Wait()
	NewClient() *Client
	//广播消息,根据包ID先发包头
	BroadMsg(m MsgIO, skips ...*Client) int
	//直接广播数据,不处理包ID
	Broadcast(m MsgIO, skips ...*Client) int
	//
	DoOpt(opt int)
	Clients() []*Client
	Addrs() []*AddrNode
}

IServer 服务器接口

func NewTCPServer

func NewTCPServer() IServer

NewTCPServer 创建TCp服务

type ISignTx

type ISignTx interface {
	SignTx(singer ISigner, pass ...string) error
}

ISignTx 签名交易

type ISigner

type ISigner interface {
	//签名校验
	Verify(bi *BlockIndex) error
	//签名生成解锁脚本
	Sign(bi *BlockIndex, lis ISignTx, pass ...string) error
	//获取签名hash
	GetSigHash() ([]byte, error)
	//获取签名对象 当前交易,当前输入,输入引用的输出,输入在交易中的索引
	GetObjs() (*TX, *TxIn, *TxOut, int)
	//检测签名 脚本调用
	VerifySign() error
	//验证地址 脚本调用
	VerifyAddr() error
	//查找交易中是否包含指定输出的地址
	QueryTxOut(addr Address) (*TxOut, error)
	//查找交易中是否包含指定输入的地址
	QueryTxIn(addr Address) (*TxIn, error)
}

ISigner 签名验证接口

func NewSigner

func NewSigner(tx *TX, out *TxOut, in *TxIn, idx int) ISigner

NewSigner 新建标准签名

type ITransListener

type ITransListener interface {
	//创建输入脚本
	NewWitnessScript(ckv *CoinKeyValue) (*WitnessScript, error)
	//获取使用的金额列表 amt=当前需要的金额
	GetCoins(amt Amount) Coins
}

ITransListener 转账监听器 先获取可使用的金额,然后获取金额相关的账户用来签名 根据转出地址获取扩展数据,剩下的金额转到找零地址

type IWriter

type IWriter interface {
	io.Writer
	io.ByteWriter
	TWrite(data interface{}) error
	Len() int
	Bytes() []byte
	Reset()
	WriteFull(dp []byte) error
}

IWriter 数据流写接口

func NewWriter

func NewWriter() IWriter

NewWriter 创建写入流

type Inventory

type Inventory struct {
	InvType uint8
	InvID   HASH256
}

Inventory 加以区块库存列表

func (*Inventory) Decode

func (m *Inventory) Decode(r IReader) error

Decode 解码消息

func (Inventory) Encode

func (m Inventory) Encode(w IWriter) error

Encode 编码消息

type Item

type Item struct {
	Object     interface{}
	Expiration int64
}

Item 缓存对象

func (Item) Expired

func (item Item) Expired() bool

Expired Returns true if the item has expired.

type Iterator

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

Iterator 查询迭代器

func (*Iterator) Close

func (it *Iterator) Close()

Close 关闭

func (*Iterator) First

func (it *Iterator) First() bool

First 第一个

func (*Iterator) Key

func (it *Iterator) Key() []byte

Key 当前Key

func (*Iterator) Last

func (it *Iterator) Last() bool

Last 最后一个

func (*Iterator) Next

func (it *Iterator) Next() bool

Next 下一个

func (*Iterator) Prev

func (it *Iterator) Prev() bool

Prev 上一个

func (*Iterator) Seek

func (it *Iterator) Seek(k []byte) bool

Seek 定位到key

func (*Iterator) Valid

func (it *Iterator) Valid() bool

Valid 是否有效

func (*Iterator) Value

func (it *Iterator) Value() []byte

Value 当前值

type LockedScript

type LockedScript struct {
	Type uint8    //类型
	Pkh  HASH160  //地址hash
	Meta VarBytes //信息数据 len < MaxMetaSize
	Exec VarBytes //解锁执行脚本
}

LockedScript 标准锁定脚本

func NewLockedScript

func NewLockedScript(pkh HASH160, meta []byte, execs ...[]byte) (*LockedScript, error)

NewLockedScript 创建锁定脚本

func (LockedScript) Address

func (ss LockedScript) Address() Address

Address 获取地址

func (*LockedScript) Decode

func (ss *LockedScript) Decode(r IReader) error

Decode 解码

func (LockedScript) Encode

func (ss LockedScript) Encode(w IWriter) error

Encode 编码

func (LockedScript) ForID

func (ss LockedScript) ForID(w IWriter) error

ForID id计算

func (LockedScript) ToScript

func (ss LockedScript) ToScript() (Script, error)

ToScript 转换为脚本存储

type MerkleTree

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

MerkleTree 默克尔树

func BuildMerkleTree

func BuildMerkleTree(ids []HASH256) *MerkleTree

BuildMerkleTree 使用多个id创建默克尔树

func GetMerkleTree

func GetMerkleTree(num int, hashs []HASH256, vb *BitSet) *MerkleTree

GetMerkleTree 从数据返回默克尔树

func NewMerkleTree

func NewMerkleTree(num int) *MerkleTree

NewMerkleTree 创建数量为num的默克尔树

func (*MerkleTree) Bits

func (tree *MerkleTree) Bits() *BitSet

Bits 返回位标记

func (*MerkleTree) Build

func (tree *MerkleTree) Build(ids []HASH256, vb *BitSet) *MerkleTree

Build 构建

func (*MerkleTree) CalcHash

func (tree *MerkleTree) CalcHash(height int, pos int, ids []HASH256) HASH256

CalcHash 结算hash

func (*MerkleTree) Extract

func (tree *MerkleTree) Extract() (HASH256, []HASH256, []int)

Extract 导出根和节点

func (*MerkleTree) ExtractRoot

func (tree *MerkleTree) ExtractRoot() (HASH256, error)

ExtractRoot 导出默克尔根

func (*MerkleTree) Hash

func (tree *MerkleTree) Hash(n1 HASH256, n2 HASH256) HASH256

Hash 结算两个hash

func (*MerkleTree) Hashs

func (tree *MerkleTree) Hashs() []HASH256

Hashs 返回hash

func (*MerkleTree) Height

func (tree *MerkleTree) Height() int

Height 返回树高度

func (MerkleTree) IsBad

func (tree MerkleTree) IsBad() bool

IsBad 是否是坏的

func (*MerkleTree) Trans

func (tree *MerkleTree) Trans() int

Trans 返回数量

func (*MerkleTree) TreeWidth

func (tree *MerkleTree) TreeWidth(height int) int

TreeWidth 获取树宽度

type MinerAct

type MinerAct struct {
	Opt int
	Arg interface{}
}

MinerAct 矿产操作

type MinerGroup

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

MinerGroup 计算群组

func NewMinerGroup

func NewMinerGroup(hb HeaderBytes, bits uint32, num int) *MinerGroup

NewMinerGroup 新建一个计算任务

func (*MinerGroup) Run

func (g *MinerGroup) Run()

Run 启动工作量计算

func (*MinerGroup) Stop

func (g *MinerGroup) Stop()

Stop 停止工作量计算

func (*MinerGroup) StopAndWait

func (g *MinerGroup) StopAndWait()

StopAndWait 停止并等待结束

func (*MinerGroup) Times

func (g *MinerGroup) Times() uint64

Times 返回hash次数

type MsgAddrs

type MsgAddrs struct {
	Addrs []NetAddr
}

MsgAddrs 返回地址

func (*MsgAddrs) Add

func (m *MsgAddrs) Add(a NetAddr) bool

Add 最多放2000个

func (*MsgAddrs) Decode

func (m *MsgAddrs) Decode(r IReader) error

Decode 解码消息

func (MsgAddrs) Encode

func (m MsgAddrs) Encode(w IWriter) error

Encode 编码消息

func (MsgAddrs) ID

func (m MsgAddrs) ID() (MsgID, error)

ID 消息ID

func (MsgAddrs) Type

func (m MsgAddrs) Type() NTType

Type 消息类型

type MsgAlert

type MsgAlert struct {
	Msg VarBytes
	Sig VarBytes //消息签名可验证消息来自哪里
}

MsgAlert 消息广播

func NewMsgAlert

func NewMsgAlert(msg string, sig *SigValue) *MsgAlert

NewMsgAlert 创建消息

func (*MsgAlert) Decode

func (m *MsgAlert) Decode(r IReader) error

Decode 解码消息

func (MsgAlert) Encode

func (m MsgAlert) Encode(w IWriter) error

Encode 编码消息

func (MsgAlert) ID

func (m MsgAlert) ID() (MsgID, error)

ID 消息ID

func (MsgAlert) Type

func (m MsgAlert) Type() NTType

Type 消息类型

func (MsgAlert) Verify

func (m MsgAlert) Verify(pub *PublicKey) error

Verify 验证消息来源

type MsgBlock

type MsgBlock struct {
	Flags uint8
	Blk   *BlockInfo
	Bytes VarBytes
}

MsgBlock 区块消息结构

func NewMsgBlock

func NewMsgBlock(blk *BlockInfo) *MsgBlock

NewMsgBlock 从区块信息创建消息

func NewMsgBlockBytes

func NewMsgBlockBytes(b []byte) *MsgBlock

NewMsgBlockBytes 从区块数据创建消息

func (*MsgBlock) AddFlags

func (m *MsgBlock) AddFlags(f uint8)

AddFlags 添加消息标记

func (*MsgBlock) Decode

func (m *MsgBlock) Decode(r IReader) error

Decode 解码

func (MsgBlock) Encode

func (m MsgBlock) Encode(w IWriter) error

Encode 编码

func (MsgBlock) ID

func (m MsgBlock) ID() (MsgID, error)

ID 消息ID

func (MsgBlock) IsNewBlock

func (m MsgBlock) IsNewBlock() bool

IsNewBlock 是否是新的区块

func (MsgBlock) IsUseBlk

func (m MsgBlock) IsUseBlk() bool

IsUseBlk 是否存储的是消息结构数据

func (MsgBlock) IsUseBytes

func (m MsgBlock) IsUseBytes() bool

IsUseBytes 是否存储的是原始数据

func (MsgBlock) Type

func (m MsgBlock) Type() NTType

Type 获取消息类型

type MsgBroadAck

type MsgBroadAck struct {
	MsgID MsgID
}

MsgBroadAck 广播应答

func (*MsgBroadAck) Decode

func (m *MsgBroadAck) Decode(r IReader) error

Decode 解码消息

func (MsgBroadAck) Encode

func (m MsgBroadAck) Encode(w IWriter) error

Encode 编码消息

func (MsgBroadAck) ID

func (m MsgBroadAck) ID() (MsgID, error)

ID 消息ID

func (MsgBroadAck) Type

func (m MsgBroadAck) Type() NTType

Type 消息类型

type MsgBroadPkg

type MsgBroadPkg struct {
	Meta  []byte //自定义的meta数据
	MsgID MsgID  //md5
}

MsgBroadPkg 广播头

func (*MsgBroadPkg) Decode

func (m *MsgBroadPkg) Decode(r IReader) error

Decode 解码消息

func (MsgBroadPkg) Encode

func (m MsgBroadPkg) Encode(w IWriter) error

Encode 编码消息

func (MsgBroadPkg) ID

func (m MsgBroadPkg) ID() (MsgID, error)

ID 消息id

func (MsgBroadPkg) Type

func (m MsgBroadPkg) Type() NTType

Type 消息类型

type MsgError

type MsgError struct {
	Code  int32    //错误代码
	Error VarBytes //错误信息
	Ext   VarBytes //扩展信息
}

MsgError 错误消息

func NewMsgError

func NewMsgError(code int, err error) *MsgError

NewMsgError 创建错误消息

func (*MsgError) Decode

func (m *MsgError) Decode(r IReader) error

Decode 解码数据

func (MsgError) Encode

func (m MsgError) Encode(w IWriter) error

Encode 编码数据

func (MsgError) ID

func (m MsgError) ID() (MsgID, error)

ID 消息ID

func (MsgError) Type

func (m MsgError) Type() NTType

Type 消息类型

type MsgFilterAdd

type MsgFilterAdd struct {
	Key VarBytes
}

MsgFilterAdd 添加过滤器key

func (*MsgFilterAdd) Decode

func (m *MsgFilterAdd) Decode(r IReader) error

Decode 解码消息

func (MsgFilterAdd) Encode

func (m MsgFilterAdd) Encode(w IWriter) error

Encode 编码消息

func (MsgFilterAdd) ID

func (m MsgFilterAdd) ID() (MsgID, error)

ID 消息ID

func (MsgFilterAdd) Type

func (m MsgFilterAdd) Type() NTType

Type 消息类型

type MsgFilterClear

type MsgFilterClear struct {
}

MsgFilterClear 清除过滤器

func (*MsgFilterClear) Decode

func (m *MsgFilterClear) Decode(r IReader) error

Decode 解码消息

func (MsgFilterClear) Encode

func (m MsgFilterClear) Encode(w IWriter) error

Encode 编码消息

func (MsgFilterClear) ID

func (m MsgFilterClear) ID() (MsgID, error)

ID 消息ID

func (MsgFilterClear) Type

func (m MsgFilterClear) Type() NTType

Type 消息类型

type MsgFilterLoad

type MsgFilterLoad struct {
	Funcs  uint32
	Tweak  uint32
	Filter VarBytes
}

MsgFilterLoad 设置过滤器,调用后client的bloom生效 过滤器设置后只会提交符合条件的信息给客户端

func (*MsgFilterLoad) Decode

func (m *MsgFilterLoad) Decode(r IReader) error

Decode 解码消息

func (MsgFilterLoad) Encode

func (m MsgFilterLoad) Encode(w IWriter) error

Encode 编码消息

func (MsgFilterLoad) ID

func (m MsgFilterLoad) ID() (MsgID, error)

ID 消息ID

func (MsgFilterLoad) Type

func (m MsgFilterLoad) Type() NTType

Type 消息类型

type MsgGetAddrs

type MsgGetAddrs struct {
}

MsgGetAddrs 获取节点记录的其他节点地址

func (*MsgGetAddrs) Decode

func (m *MsgGetAddrs) Decode(r IReader) error

Decode 解码消息

func (MsgGetAddrs) Encode

func (m MsgGetAddrs) Encode(w IWriter) error

Encode 编码消息

func (MsgGetAddrs) ID

func (m MsgGetAddrs) ID() (MsgID, error)

ID 返回消息id

func (MsgGetAddrs) Type

func (m MsgGetAddrs) Type() NTType

Type 获取消息类型

type MsgGetBlock

type MsgGetBlock struct {
	Last  HASH256
	Next  uint32
	Count uint32 //获取数量
}

MsgGetBlock 获取区块消息

func (*MsgGetBlock) Decode

func (m *MsgGetBlock) Decode(r IReader) error

Decode 解码消息

func (MsgGetBlock) Encode

func (m MsgGetBlock) Encode(w IWriter) error

Encode 编码消息

func (MsgGetBlock) ID

func (m MsgGetBlock) ID() (MsgID, error)

ID 消息ID

func (MsgGetBlock) Type

func (m MsgGetBlock) Type() NTType

Type 消息类型

type MsgGetInv

type MsgGetInv struct {
	Invs []Inventory
}

MsgGetInv 获取库存

func (*MsgGetInv) AddInv

func (m *MsgGetInv) AddInv(typ uint8, id HASH256)

AddInv 添加库存

func (*MsgGetInv) Decode

func (m *MsgGetInv) Decode(r IReader) error

Decode 解码消息

func (MsgGetInv) Encode

func (m MsgGetInv) Encode(w IWriter) error

Encode 编码消息

func (MsgGetInv) ID

func (m MsgGetInv) ID() (MsgID, error)

ID 消息ID

func (MsgGetInv) Type

func (m MsgGetInv) Type() NTType

Type 消息类型

type MsgGetMerkle

type MsgGetMerkle struct {
	TxID HASH256 //交易id
}

MsgGetMerkle 获取交易验证merkle树

func (*MsgGetMerkle) Decode

func (m *MsgGetMerkle) Decode(r IReader) error

Decode 解码消息

func (MsgGetMerkle) Encode

func (m MsgGetMerkle) Encode(w IWriter) error

Encode 编码消息

func (MsgGetMerkle) ID

func (m MsgGetMerkle) ID() (MsgID, error)

ID 消息ID

func (MsgGetMerkle) Type

func (m MsgGetMerkle) Type() NTType

Type 消息类型

type MsgGetTxPool

type MsgGetTxPool struct {
	Skip []HASH256 //忽略的交易id
}

MsgGetTxPool 获取本节点没有的

func (*MsgGetTxPool) Add

func (m *MsgGetTxPool) Add(id HASH256)

Add 添加不需要的交易Id

func (*MsgGetTxPool) Decode

func (m *MsgGetTxPool) Decode(r IReader) error

Decode 解码消息

func (MsgGetTxPool) Encode

func (m MsgGetTxPool) Encode(w IWriter) error

Encode 编码消息

func (MsgGetTxPool) Has

func (m MsgGetTxPool) Has(id HASH256) bool

Has 检测id是否在忽略列表中

func (MsgGetTxPool) ID

func (m MsgGetTxPool) ID() (MsgID, error)

ID 消息ID

func (MsgGetTxPool) Type

func (m MsgGetTxPool) Type() NTType

Type 消息类型

type MsgHeaders

type MsgHeaders struct {
	Headers Headers
	//上次请求参数
	Info MsgGetBlock
}

MsgHeaders 获取区块头网络结构

func (*MsgHeaders) Decode

func (m *MsgHeaders) Decode(r IReader) error

Decode 解码

func (MsgHeaders) Encode

func (m MsgHeaders) Encode(w IWriter) error

Encode 编码

func (MsgHeaders) ID

func (m MsgHeaders) ID() (MsgID, error)

ID 获取消息ID

func (MsgHeaders) Type

func (m MsgHeaders) Type() NTType

Type 消息类型

type MsgID

type MsgID [md5.Size]byte

MsgID 消息ID定义 使用md5

func GetDefautMsgID

func GetDefautMsgID(m MsgIO) (MsgID, error)

GetDefautMsgID 获取默认msgid

func MsgIDFromHex

func MsgIDFromHex(str string) MsgID

func (MsgID) RecvKey

func (m MsgID) RecvKey() string

RecvKey 用于接收的key

func (MsgID) SendKey

func (m MsgID) SendKey() string

SendKey 用于发送的key

func (MsgID) String

func (id MsgID) String() string

type MsgIO

type MsgIO interface {
	ISerializable
	ID() (MsgID, error) //广播id获取
	Type() NTType
}

MsgIO 协议消息

type MsgInv

type MsgInv struct {
	Invs []Inventory
}

MsgInv 交易消息

func (*MsgInv) AddInv

func (m *MsgInv) AddInv(typ uint8, id HASH256)

AddInv 添加

func (*MsgInv) Decode

func (m *MsgInv) Decode(r IReader) error

Decode 解码

func (MsgInv) Encode

func (m MsgInv) Encode(w IWriter) error

Encode 编码

func (MsgInv) ID

func (m MsgInv) ID() (MsgID, error)

ID 消息ID

func (MsgInv) Type

func (m MsgInv) Type() NTType

Type 消息类型

type MsgPing

type MsgPing struct {
	Time   int64
	Height uint32 //发送我的最新高度
}

MsgPing ping消息

func NewMsgPing

func NewMsgPing(h uint32) *MsgPing

NewMsgPing 创建ping消息

func (*MsgPing) Decode

func (v *MsgPing) Decode(r IReader) error

Decode 解码ping消息

func (MsgPing) Encode

func (v MsgPing) Encode(w IWriter) error

Encode 编码ping消息

func (MsgPing) ID

func (v MsgPing) ID() (MsgID, error)

ID 消息ID

func (MsgPing) NewPong

func (v MsgPing) NewPong(h uint32) *MsgPong

NewPong 收到ping时创建pong消息返回

func (MsgPing) Type

func (v MsgPing) Type() NTType

Type 消息类型

type MsgPong

type MsgPong struct {
	Time   int64
	Height uint32 //获取对方的高度
}

MsgPong 收到ping消息返回

func (*MsgPong) Decode

func (v *MsgPong) Decode(r IReader) error

Decode 解码

func (MsgPong) Encode

func (v MsgPong) Encode(w IWriter) error

Encode 编码

func (MsgPong) ID

func (v MsgPong) ID() (MsgID, error)

ID 消息id

func (MsgPong) Ping

func (v MsgPong) Ping() int

Ping 获取ping值

func (MsgPong) Type

func (v MsgPong) Type() NTType

Type 消息类型

type MsgTx

type MsgTx struct {
	Txs []*TX
}

MsgTx 交易信息

func NewMsgTx

func NewMsgTx(tx *TX) *MsgTx

NewMsgTx 从tx创建交易消息

func (*MsgTx) Add

func (m *MsgTx) Add(tx *TX)

Add 添加交易

func (*MsgTx) Decode

func (m *MsgTx) Decode(r IReader) error

Decode 解码消息

func (MsgTx) Encode

func (m MsgTx) Encode(w IWriter) error

Encode 编码消息

func (MsgTx) ID

func (m MsgTx) ID() (MsgID, error)

ID 交易ID

func (MsgTx) Type

func (m MsgTx) Type() NTType

Type 消息类型

type MsgTxMerkle

type MsgTxMerkle struct {
	TxID  HASH256   //当前交易id
	Trans VarInt    //交易锁在块的交易数量
	Hashs []HASH256 //基于merkle树的验证hash
	Bits  VarBytes  //
}

MsgTxMerkle 返回交易验证merkle树

func (*MsgTxMerkle) Decode

func (m *MsgTxMerkle) Decode(r IReader) error

Decode 解码消息

func (MsgTxMerkle) Encode

func (m MsgTxMerkle) Encode(w IWriter) error

Encode 编码消息

func (MsgTxMerkle) ID

func (m MsgTxMerkle) ID() (MsgID, error)

ID 消息ID

func (MsgTxMerkle) Type

func (m MsgTxMerkle) Type() NTType

Type 消息类型

func (MsgTxMerkle) Verify

func (m MsgTxMerkle) Verify(bi *BlockIndex) error

Verify 验证数据

type MsgTxPool

type MsgTxPool struct {
	Txs []*TX
}

MsgTxPool 返回交易池数据

func (*MsgTxPool) Add

func (m *MsgTxPool) Add(tx *TX)

Add 添加交易

func (*MsgTxPool) Decode

func (m *MsgTxPool) Decode(r IReader) error

Decode 解码消息

func (MsgTxPool) Encode

func (m MsgTxPool) Encode(w IWriter) error

Encode 编码消息

func (MsgTxPool) ID

func (m MsgTxPool) ID() (MsgID, error)

ID 消息ID

func (MsgTxPool) Type

func (m MsgTxPool) Type() NTType

Type 消息类型

type MsgVersion

type MsgVersion struct {
	Ver     uint32  //版本
	Service uint32  //服务
	Addr    NetAddr //节点外网地址
	Height  uint32  //节点区块高度
	NodeID  uint64  //节点id
	Tps     VarUInt //交易池数量
}

MsgVersion 版本消息包

func (*MsgVersion) Decode

func (v *MsgVersion) Decode(r IReader) error

Decode 解码数据

func (MsgVersion) Encode

func (v MsgVersion) Encode(w IWriter) error

Encode 编码

func (MsgVersion) ID

func (v MsgVersion) ID() (MsgID, error)

ID 消息ID

func (MsgVersion) Type

func (v MsgVersion) Type() NTType

Type 消息类型

type NTType

type NTType uint8

NTType 消息类型

func (NTType) String

func (t NTType) String() string

type NetAddr

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

NetAddr 地址定义

func NetAddrForm

func NetAddrForm(s string) NetAddr

NetAddrForm 解析地址

func (NetAddr) Addr

func (c NetAddr) Addr(h ...string) string

Addr 获取地址

func (*NetAddr) Decode

func (c *NetAddr) Decode(r IReader) error

Decode 解码网络地址

func (NetAddr) Encode

func (c NetAddr) Encode(w IWriter) error

Encode 编码网络地址

func (NetAddr) Equal

func (c NetAddr) Equal(d NetAddr) bool

Equal ==

func (*NetAddr) From

func (c *NetAddr) From(s string) error

From 解析地址

func (NetAddr) IP

func (c NetAddr) IP() []byte

IP 获取ip

func (NetAddr) IsGlobalUnicast

func (c NetAddr) IsGlobalUnicast() bool

IsGlobalUnicast 是否是有效的可链接的地址

func (NetAddr) Network

func (c NetAddr) Network() string

Network 网络类型

func (NetAddr) String

func (c NetAddr) String() string

func (NetAddr) ToTCPAddr

func (c NetAddr) ToTCPAddr() *net.TCPAddr

ToTCPAddr 转换为Tcp结构

type NetPackage

type NetPackage struct {
	Flags [4]byte  //标识
	Type  NTType   //包类型
	Bytes VarBytes //数据长度
	Attr  uint8    //数据特性
	Sum   uint32   //校验和
}

NetPackage 网络数据包定义

func (*NetPackage) Decode

func (v *NetPackage) Decode(r IReader) error

Decode 解码网络数据包

func (NetPackage) Encode

func (v NetPackage) Encode(w IWriter) error

Encode 编码网络数据包

func (NetPackage) IsZip

func (v NetPackage) IsZip() bool

IsZip 是否启用压缩, Attr 设置后可用

func (*NetPackage) Sum32

func (v *NetPackage) Sum32() uint32

Sum32 计算校验和

func (NetPackage) ToMsgIO

func (v NetPackage) ToMsgIO() (MsgIO, error)

ToMsgIO 转为类型

type NetStream

type NetStream struct {
	net.Conn
	// contains filtered or unexported fields
}

NetStream 网络读写流

func NewNetStream

func NewNetStream(conn net.Conn) *NetStream

NewNetStream 从网络连接创建网络流

func (*NetStream) Bytes

func (s *NetStream) Bytes() []byte

Bytes 最后一个数据包数据

func (*NetStream) Len

func (s *NetStream) Len() int

Len 读写的数据长度

func (*NetStream) ReadByte

func (s *NetStream) ReadByte() (byte, error)

ReadByte 读取一个字节

func (*NetStream) ReadFull

func (s *NetStream) ReadFull(dp []byte) error

ReadFull 完整读取

func (*NetStream) ReadMsg

func (s *NetStream) ReadMsg(attr ...*uint8) (MsgIO, error)

ReadMsg 从网络流读取数据包

func (*NetStream) Reset

func (s *NetStream) Reset()

Reset 重置数据流状态

func (*NetStream) TRead

func (s *NetStream) TRead(data interface{}) error

TRead 按类型读

func (*NetStream) TWrite

func (s *NetStream) TWrite(data interface{}) error

TWrite 按类型写入

func (*NetStream) WriteByte

func (s *NetStream) WriteByte(b byte) error

WriteByte 写入一个字节

func (*NetStream) WriteFull

func (s *NetStream) WriteFull(dp []byte) error

WriteFull 完整写入

func (*NetStream) WriteMsg

func (s *NetStream) WriteMsg(m MsgIO, attrs ...uint8) error

WriteMsg 写消息到网路

type ONCE

type ONCE int32

ONCE 防止被多个线程同时执行

func (*ONCE) IsRunning

func (f *ONCE) IsRunning() bool

IsRunning 是否在运行

func (*ONCE) Reset

func (f *ONCE) Reset()

Reset 重置

func (*ONCE) Running

func (f *ONCE) Running() bool

Running 如果没运行返回false,否则设置为允许并返回true

type PKBytes

type PKBytes [33]byte

PKBytes 公钥字节存储

func (PKBytes) Bytes

func (v PKBytes) Bytes() []byte

Bytes 获取字节

func (PKBytes) Cmp

func (v PKBytes) Cmp(b PKBytes) int

Cmp 转为大数比较

func (*PKBytes) Decode

func (v *PKBytes) Decode(r IReader) error

Decode 解码数据

func (PKBytes) Encode

func (v PKBytes) Encode(w IWriter) error

Encode 编码

func (PKBytes) Equal

func (v PKBytes) Equal(b PKBytes) bool

Equal ==

func (PKBytes) Hash

func (v PKBytes) Hash() HASH160

Hash 计算 hash

func (PKBytes) Hash256

func (v PKBytes) Hash256() HASH256

Hash 计算 hash

func (PKBytes) IsValid

func (v PKBytes) IsValid() bool

func (*PKBytes) Set

func (v *PKBytes) Set(pk *PublicKey) PKBytes

Set 使用公钥初始化

func (*PKBytes) SetBytes

func (v *PKBytes) SetBytes(b []byte)

SetBytes 使用二进制初始化数据

type PrivateKey

type PrivateKey struct {
	D *big.Int
}

PrivateKey 私钥

func LoadPrivateKey

func LoadPrivateKey(s string, pass ...string) (*PrivateKey, error)

LoadPrivateKey 加载私钥

func NewPrivateKey

func NewPrivateKey() (*PrivateKey, error)

NewPrivateKey 创建私钥

func NewPrivateKeyWithBytes

func NewPrivateKeyWithBytes(b []byte) (*PrivateKey, error)

NewPrivateKeyWithBytes 使用二进制创建私钥

func (*PrivateKey) Bytes

func (pk *PrivateKey) Bytes() []byte

Bytes 获取二进制数据

func (*PrivateKey) Clone

func (pk *PrivateKey) Clone() *PrivateKey

Clone 复制私钥

func (*PrivateKey) Decode

func (pk *PrivateKey) Decode(data []byte) error

Decode 解码私钥

func (*PrivateKey) Dump

func (pk *PrivateKey) Dump(pass ...string) (string, error)

Dump 导出私钥

func (*PrivateKey) Encode

func (pk *PrivateKey) Encode() []byte

Encode 编码数据

func (*PrivateKey) IsValid

func (pk *PrivateKey) IsValid() bool

IsValid 是否有效

func (*PrivateKey) Load

func (pk *PrivateKey) Load(s string, pass ...string) error

Load 加载私钥

func (PrivateKey) Marshal

func (pk PrivateKey) Marshal() []byte

Marshal 编码数据

func (PrivateKey) New

func (pk PrivateKey) New(plus []byte) *PrivateKey

New 当前私钥基础上hash新的私钥

func (*PrivateKey) PublicKey

func (pk *PrivateKey) PublicKey() *PublicKey

PublicKey 获取私钥对应的公钥

func (*PrivateKey) SetBytes

func (pk *PrivateKey) SetBytes(b []byte) *PrivateKey

SetBytes 二进制初始化

func (PrivateKey) Sign

func (pk PrivateKey) Sign(hash []byte) (*SigValue, error)

Sign 签名hash256数据

func (PrivateKey) String

func (pk PrivateKey) String() string

type PrivatesMap

type PrivatesMap map[HASH160]*PrivateKey

PrivatesMap 私钥存储结构

type PubSub

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

PubSub is a collection of topics.

func GetPubSub

func GetPubSub() *PubSub

GetPubSub 获取全局发布订阅

func NewPubSub

func NewPubSub(capacity int) *PubSub

NewPubSub creates a new PubSub and starts a goroutine for handling operations. The capacity of the channels created by Sub and SubOnce will be as specified.

func (*PubSub) AddSub

func (ps *PubSub) AddSub(ch chan interface{}, topics ...string)

AddSub adds subscriptions to an existing channel.

func (*PubSub) AddSubOnceEach

func (ps *PubSub) AddSubOnceEach(ch chan interface{}, topics ...string)

AddSubOnceEach adds subscriptions to an existing channel with SubOnceEach behavior.

func (*PubSub) Close

func (ps *PubSub) Close(topics ...string)

Close closes all channels currently subscribed to the specified topics. If a channel is subscribed to multiple topics, some of which is not specified, it is not closed.

func (*PubSub) Pub

func (ps *PubSub) Pub(msg interface{}, topics ...string)

Pub publishes the given message to all subscribers of the specified topics.

func (*PubSub) Shutdown

func (ps *PubSub) Shutdown()

Shutdown closes all subscribed channels and terminates the goroutine.

func (*PubSub) Sub

func (ps *PubSub) Sub(topics ...string) chan interface{}

Sub returns a channel on which messages published on any of the specified topics can be received.

func (*PubSub) SubOnce

func (ps *PubSub) SubOnce(topics ...string) chan interface{}

SubOnce is similar to Sub, but only the first message published, after subscription, on any of the specified topics can be received.

func (*PubSub) SubOnceEach

func (ps *PubSub) SubOnceEach(topics ...string) chan interface{}

SubOnceEach returns a channel on which callers receive, at most, one message for each topic.

func (*PubSub) TryPub

func (ps *PubSub) TryPub(msg interface{}, topics ...string)

TryPub publishes the given message to all subscribers of the specified topics if the topic has buffer space.

func (*PubSub) Unsub

func (ps *PubSub) Unsub(ch chan interface{}, topics ...string)

Unsub unsubscribes the given channel from the specified topics. If no topic is specified, it is unsubscribed from all topics.

Unsub must be called from a goroutine that is different from the subscriber. The subscriber must consume messages from the channel until it reaches the end. Not doing so can result in a deadlock.

type PublicArray

type PublicArray []*PublicKey

PublicArray 公钥数据

type PublicKey

type PublicKey struct {
	X *big.Int
	Y *big.Int
	// contains filtered or unexported fields
}

PublicKey 公钥

func LoadPublicKey

func LoadPublicKey(s string, pass ...string) (*PublicKey, error)

LoadPublicKey 加载公钥数据

func NewPublicKey

func NewPublicKey(data []byte) (*PublicKey, error)

NewPublicKey 从二进制创建公钥

func (*PublicKey) Decode

func (pk *PublicKey) Decode(data []byte) error

Decode 解码公钥

func (*PublicKey) Dump

func (pk *PublicKey) Dump(pass ...string) (string, error)

Dump 导出公钥

func (*PublicKey) Encode

func (pk *PublicKey) Encode() []byte

Encode 编码公钥

func (*PublicKey) Equal

func (pk *PublicKey) Equal(sb []byte) bool

Equal ==

func (*PublicKey) FromHEX

func (pk *PublicKey) FromHEX(s string) error

FromHEX 从16进制格式创建私钥

func (*PublicKey) GetPks

func (pk *PublicKey) GetPks() PKBytes

GetPks 获取公钥数据

func (*PublicKey) Hash

func (pk *PublicKey) Hash() HASH160

Hash hash公钥

func (*PublicKey) ID

func (pk *PublicKey) ID() (string, error)

ID 获取公钥ID

func (*PublicKey) IsValid

func (pk *PublicKey) IsValid() bool

IsValid 检查公钥是否有效

func (*PublicKey) Load

func (pk *PublicKey) Load(s string, pass ...string) (*PublicKey, error)

Load 加载公钥

func (*PublicKey) Verify

func (pk *PublicKey) Verify(hash []byte, sig *SigValue) bool

Verify 验证hash签名

type RSAPrivateKey

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

RSAPrivateKey rsa私钥

func LoadRSAPrivateKey

func LoadRSAPrivateKey(str string, pass ...string) (*RSAPrivateKey, error)

LoadRSAPrivateKey 加载一个私钥

func NewRSAPrivateKey

func NewRSAPrivateKey() (*RSAPrivateKey, error)

NewRSAPrivateKey 创建一个rsa密钥对

func (RSAPrivateKey) Decrypt

func (ptr RSAPrivateKey) Decrypt(bb []byte) ([]byte, error)

Decrypt 私钥解密

func (RSAPrivateKey) Dump

func (ptr RSAPrivateKey) Dump(pass ...string) (string, error)

Dump 导出密钥

func (RSAPrivateKey) ID

func (ptr RSAPrivateKey) ID() (string, error)

ID 获取RSA ID

func (*RSAPrivateKey) Load

func (ptr *RSAPrivateKey) Load(str string, pass ...string) error

Load 加载rsa私钥

func (RSAPrivateKey) PublicKey

func (ptr RSAPrivateKey) PublicKey() *RSAPublicKey

PublicKey 获取对应的公钥

func (RSAPrivateKey) Sign

func (ptr RSAPrivateKey) Sign(src []byte) ([]byte, error)

Sign 私钥签名

type RSAPublicKey

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

RSAPublicKey rsa公钥

func LoadRSAPublicKey

func LoadRSAPublicKey(str string) (*RSAPublicKey, error)

LoadRSAPublicKey 加载一个公钥

func (RSAPublicKey) Dump

func (ptr RSAPublicKey) Dump() (string, error)

Dump 导出公钥

func (RSAPublicKey) Encrypt

func (ptr RSAPublicKey) Encrypt(bb []byte) ([]byte, error)

Encrypt 公钥加密

func (RSAPublicKey) ID

func (ptr RSAPublicKey) ID() (string, error)

func (*RSAPublicKey) Load

func (ptr *RSAPublicKey) Load(str string) error

Load 加载公钥

func (RSAPublicKey) MustID

func (ptr RSAPublicKey) MustID() string

func (RSAPublicKey) Verify

func (ptr RSAPublicKey) Verify(src []byte, sign []byte) error

Verify 公钥验签

type Range

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

Range 查询范围

func NewPrefix

func NewPrefix(p []byte) *Range

NewPrefix 创建按前缀的范围

func NewRange

func NewRange(s []byte, l []byte) *Range

NewRange 创建一个范围

type Script

type Script []byte

Script 脚本定义

func NewCoinbaseScript

func NewCoinbaseScript(h uint32, ip []byte, bs ...[]byte) (Script, error)

NewCoinbaseScript 创建coinbase脚本

func NewTxScript

func NewTxScript(exeLimit uint32, execs ...[]byte) (Script, error)

NewTxScript 创建交易脚本

func (Script) Check

func (s Script) Check() error

Check 检测脚本错误

func (Script) Clone

func (s Script) Clone() Script

Clone 复制脚本

func (Script) Data

func (s Script) Data() []byte

Data 获取coinbase中的自定义数据

func (*Script) Decode

func (s *Script) Decode(r IReader) error

Decode 解码脚本

func (Script) Encode

func (s Script) Encode(w IWriter) error

Encode 编码脚本

func (Script) ForID

func (s Script) ForID(w IWriter) error

ForID 为计算id编码脚本数据

func (Script) ForVerify

func (s Script) ForVerify(w IWriter) error

ForVerify 脚本签名数据

func (Script) GetAddress

func (s Script) GetAddress() (Address, error)

GetAddress 从锁定脚本获取输出地址

func (Script) GetPkh

func (s Script) GetPkh() (HASH160, error)

GetPkh coinbase交易没有pkh

func (Script) GetType

func (s Script) GetType() uint8

获取脚本类型

func (Script) Height

func (s Script) Height() uint32

Height 获取coinbase中的区块高度

func (Script) IP

func (s Script) IP() []byte

IP 获取coinbase中的区块高度

func (Script) IsCoinBase

func (s Script) IsCoinBase() bool

IsCoinBase 是否是coinbase脚本

func (Script) IsLocked

func (s Script) IsLocked() bool

IsLocked 是否是锁定脚本

func (Script) IsTxScript

func (s Script) IsTxScript() bool

IsTxScript 是否是交易脚本

func (Script) IsWitness

func (s Script) IsWitness() bool

IsWitness 是否是隔离见证脚本

func (Script) Len

func (s Script) Len() int

Len 脚本长度

func (Script) MustPkh

func (s Script) MustPkh() HASH160

MustPkh 获取公钥hash

func (Script) To

func (s Script) To() (interface{}, error)

To 转换到任意类型

func (Script) ToLocked

func (s Script) ToLocked() (*LockedScript, error)

ToLocked 如果是锁定脚本

func (Script) ToTxScript

func (s Script) ToTxScript() (*TxScript, error)

ToTxScript 如果是锁定脚本

func (Script) ToWitness

func (s Script) ToWitness() (*WitnessScript, error)

ToWitness 如果是隔离见证脚本

func (Script) Type

func (s Script) Type() uint8

Type 脚本类型

type SigBytes

type SigBytes [75]byte

SigBytes 签名数据

func (SigBytes) Bytes

func (v SigBytes) Bytes() []byte

Bytes 获取二进制

func (*SigBytes) Decode

func (v *SigBytes) Decode(r IReader) error

Decode 解码签名数据

func (SigBytes) Encode

func (v SigBytes) Encode(w IWriter) error

Encode 编码数据

func (SigBytes) IsValid

func (v SigBytes) IsValid() bool

func (*SigBytes) Set

func (v *SigBytes) Set(sig *SigValue)

Set 使用签名初始化

func (*SigBytes) SetBytes

func (v *SigBytes) SetBytes(b []byte)

SetBytes 使用二进制初始化

type SigValue

type SigValue struct {
	R *big.Int
	S *big.Int
}

SigValue 签名

func NewSigValue

func NewSigValue(b []byte) (*SigValue, error)

NewSigValue 从二进制创建签名

func (*SigValue) CheckLow

func (sig *SigValue) CheckLow(b []byte) (int, int, error)

CheckLow 检测签名数据

func (*SigValue) Decode

func (sig *SigValue) Decode(b []byte) error

Decode 解码签名

func (SigValue) Encode

func (sig SigValue) Encode() []byte

Encode 编码签名

func (*SigValue) FromHEX

func (sig *SigValue) FromHEX(s string) error

FromHEX 从hex格式创建

func (*SigValue) GetSigs

func (sig *SigValue) GetSigs() SigBytes

GetSigs 导出签名数据

type TBEle

type TBEle struct {
	TBMeta
	Height uint32
	// contains filtered or unexported fields
}

TBEle 索引头

func EmptyTBEle

func EmptyTBEle(h uint32, bh BlockHeader, bi *BlockIndex) *TBEle

EmptyTBEle 创建一个空的链表结构

func NewTBEle

func NewTBEle(meta *TBMeta, height uint32, bi *BlockIndex) *TBEle

NewTBEle 创建一个链表结构

func (*TBEle) LoadMeta

func (ele *TBEle) LoadMeta(id HASH256) error

LoadMeta 从磁盘加载块头

func (TBEle) String

func (ele TBEle) String() string

type TBMeta

type TBMeta struct {
	BlockHeader          //区块头
	Txs         VarUInt  //tx数量
	Blk         BlkChunk //数据状态
	Rev         BlkChunk //日志回退
	// contains filtered or unexported fields
}

TBMeta 区块头存储类型

func (TBMeta) Bytes

func (h TBMeta) Bytes() ([]byte, error)

Bytes 返回编码数据

func (*TBMeta) Decode

func (h *TBMeta) Decode(r IReader) error

Decode 解码

func (TBMeta) Encode

func (h TBMeta) Encode(w IWriter) error

Encode 编码

func (TBMeta) HasBlk

func (h TBMeta) HasBlk() bool

HasBlk 是否有区块数据

func (TBMeta) HasRev

func (h TBMeta) HasRev() bool

HasRev 是否有回退数据

func (*TBMeta) Hash

func (h *TBMeta) Hash() HASH256

Hash 计算hash

func (TBMeta) String

func (h TBMeta) String() string

type TCPServer

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

TCPServer 基于tcp的服务

func (*TCPServer) Addrs

func (s *TCPServer) Addrs() []*AddrNode

Addrs 获取节点保存的地址

func (*TCPServer) BroadMsg

func (s *TCPServer) BroadMsg(m MsgIO, skips ...*Client) int

BroadMsg 如果skips不空不会广播给skips中的链接

func (*TCPServer) Broadcast

func (s *TCPServer) Broadcast(m MsgIO, skips ...*Client) int

Broad 直接广播数据,不处理包头

func (*TCPServer) Clients

func (s *TCPServer) Clients() []*Client

Clients 获取连接的客户端

func (*TCPServer) ConnNum

func (s *TCPServer) ConnNum() int

ConnNum 活跃连接地址数量

func (*TCPServer) DelClient

func (s *TCPServer) DelClient(id uint64, c *Client)

DelClient 移除客户端

func (*TCPServer) DoOpt

func (s *TCPServer) DoOpt(opt int)

DoOpt 操作通道

func (*TCPServer) GetPkg

func (s *TCPServer) GetPkg(id string) (MsgIO, bool)

GetPkg 获取广播数据包

func (*TCPServer) HasClient

func (s *TCPServer) HasClient(id uint64, c *Client) bool

HasClient 是否存在客户端

func (*TCPServer) HasPkg

func (s *TCPServer) HasPkg(id string) bool

HasPkg 是否有广播数据包

func (*TCPServer) IsAddrOpen

func (s *TCPServer) IsAddrOpen(addr NetAddr) bool

IsAddrOpen 地址是否已经链接

func (*TCPServer) IsOpen

func (s *TCPServer) IsOpen(id uint64) bool

IsOpen 地址是否打开

func (*TCPServer) NewClient

func (s *TCPServer) NewClient() *Client

NewClient 创建客户端用来连接其他服务器

func (*TCPServer) NewClientWithConn

func (s *TCPServer) NewClientWithConn(conn net.Conn) *Client

NewClientWithConn 从网络连接创建客户端

func (*TCPServer) NewMsgAddrs

func (s *TCPServer) NewMsgAddrs(c *Client) *MsgAddrs

NewMsgAddrs 创建地址列表消息

func (*TCPServer) Run

func (s *TCPServer) Run()

Run 启动服务

func (*TCPServer) SetPkg

func (s *TCPServer) SetPkg(id string, m MsgIO)

SetPkg 保存广播数据包

func (*TCPServer) Start

func (s *TCPServer) Start(ctx context.Context, lptr IListener)

Start 启动服务

func (*TCPServer) Stop

func (s *TCPServer) Stop()

Stop 地址服务

func (*TCPServer) Wait

func (s *TCPServer) Wait()

Wait 等待服务停止

type TRImp

type TRImp interface {
	Has(ks ...[]byte) (bool, error)
	Put(ks ...[]byte) error
	Get(ks ...[]byte) ([]byte, error)
	Del(ks ...[]byte) error
	Write(b *Batch, sync ...bool) error
	Iterator(slice ...*Range) *Iterator
	Commit() error
	Discard()
}

TRImp 事务接口

type TX

type TX struct {
	Ver    VarUInt  //版本
	Ins    []*TxIn  //输入
	Outs   []*TxOut //输出
	Script Script   //交易执行脚本,执行失败不会进入交易池
	// contains filtered or unexported fields
}

TX 交易

func NewTx

func NewTx(exeLimit uint32, execs ...[]byte) *TX

NewTx 创建交易 exeLimit 执行脚本限制

func (*TX) Check

func (tx *TX) Check(bi *BlockIndex, csp bool) error

Check 检测除coinbase交易外的交易金额 csp是否检测输出金额是否已经被消费,如果交易已经打包进区块,输入引用的输出肯定被消费,coin将不存在 clk 是否检查seqlock

func (TX) Clone

func (tx TX) Clone(seq ...uint) *TX

Clone 复制交易 seq 如果需要自增输入的Sequence设置

func (*TX) CoinbaseFee

func (tx *TX) CoinbaseFee() (Amount, error)

CoinbaseFee 获取coinse out fee sum

func (*TX) CoinsIsValid

func (tx *TX) CoinsIsValid(bi *BlockIndex) bool

验证输入对应的金额是否存在,不验证签名

func (*TX) Decode

func (tx *TX) Decode(r IReader) error

Decode 解码交易数据

func (*TX) Encode

func (tx *TX) Encode(w IWriter) error

Encode 编码交易数据

func (*TX) ExecScript

func (tx *TX) ExecScript(bi *BlockIndex) error

ExecScript 返回错误交易不进入区块 执行之前已经校验了签名 AddTxs LinkBlk 时会执行这个交易脚本检测

func (*TX) GetFeeAmount

func (tx *TX) GetFeeAmount(bi *BlockIndex) (Amount, error)

GetFeeAmount 获取此交易交易费 如果是coinase返回coinbase输出金额

func (*TX) HasRepTxIn

func (tx *TX) HasRepTxIn(bi *BlockIndex, csp bool) bool

HasRepTxIn 检测交易中是否有重复的输入

func (*TX) ID

func (tx *TX) ID() (HASH256, error)

ID 交易id计算,不包括见证数据

func (*TX) IsCoinBase

func (tx *TX) IsCoinBase() bool

IsCoinBase 是否是coinbase交易

func (TX) IsFinal

func (tx TX) IsFinal() bool

IsFinal 返回true表示交易生效不能替换

func (TX) IsPool

func (tx TX) IsPool() bool

IsPool 是否来自交易池

func (TX) IsReplace

func (tx TX) IsReplace(old *TX) bool

IsReplace 当前交易是否可替换原来的交易 这个替换只能交易池中执行,执行之前签名已经通过 交易一但被打包到区块就不能替换了,但可能会回退

func (*TX) MustID

func (tx *TX) MustID() HASH256

MustID 必须获取到交易ID

func (*TX) ResetAll

func (tx *TX) ResetAll()

ResetAll 重所有置缓存

func (*TX) ResetSign

func (tx *TX) ResetSign()

ResetSign 重置缓存

func (*TX) Sign

func (tx *TX) Sign(bi *BlockIndex, lis ISignTx, pass ...string) error

Sign 签名交易数据 cspent 是否检测输出金额是否存在

func (TX) String

func (tx TX) String() string

func (*TX) Verify

func (tx *TX) Verify(bi *BlockIndex) error

Verify 验证交易签名数据

type TestLis

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

TestLis 测试用监听器

func GetTestListener

func GetTestListener(bi *BlockIndex) *TestLis

GetTestListener 获取测试监听

func (*TestLis) GetAccount

func (lis *TestLis) GetAccount(i int) *Account

GetAccount 获取测试账户0-4

func (*TestLis) MinerAddr

func (lis *TestLis) MinerAddr() Address

GetAccount 获取测试账户0-4

func (*TestLis) OnClientMsg

func (lis *TestLis) OnClientMsg(c *Client, msg MsgIO)

当收到网络数据时,数据包根据类型转换成需要的包

func (*TestLis) OnClose

func (lis *TestLis) OnClose()

链关闭时

func (*TestLis) OnFinished

func (lis *TestLis) OnFinished(blk *BlockInfo) error

完成区块,当检测完成调用,设置merkle之前

func (*TestLis) OnInit

func (lis *TestLis) OnInit(bi *BlockIndex) error

OnInit 测试用

func (*TestLis) OnLinkBlock

func (lis *TestLis) OnLinkBlock(blk *BlockInfo)

更新区块数据成功时

func (*TestLis) OnLoadTxs

func (lis *TestLis) OnLoadTxs(txs []*TX) []*TX

当加载交易列表到区块时可用此方法过滤不加入区块的 调用 AddTxs 时会触发

func (*TestLis) OnNewBlock

func (lis *TestLis) OnNewBlock(blk *BlockInfo) error

当块创建时,可以添加,修改块内信息

func (*TestLis) OnSignTx

func (lis *TestLis) OnSignTx(signer ISigner) error

OnSignTx 签名器

func (*TestLis) OnStart

func (lis *TestLis) OnStart()

当服务启动后会调用一次

func (*TestLis) OnStop

func (lis *TestLis) OnStop()

系统结束时

func (*TestLis) OnTxPool

func (lis *TestLis) OnTxPool(tx *TX) error

当交易进入交易池之前,返回错误不会进入交易池

func (*TestLis) OnTxPoolRep

func (lis *TestLis) OnTxPoolRep(old *TX, new *TX)

当交易池的交易被替换时

func (*TestLis) OnUnlinkBlock

func (lis *TestLis) OnUnlinkBlock(blk *BlockInfo)

func (*TestLis) TimeNow

func (lis *TestLis) TimeNow() uint32

TimeNow 测试用时间返回

type Trans

type Trans struct {
	Dst   []Address //目标地址
	Amt   []Amount  //目标金额 大小与dst对应
	Metas []string
	Fee   Amount //交易费
	// contains filtered or unexported fields
}

Trans 交易数据结构

func (*Trans) Add

func (m *Trans) Add(dst Address, amt Amount, meta ...string)

Add 设置一个转账对象

func (*Trans) BroadTx

func (m *Trans) BroadTx(bi *BlockIndex, tx *TX)

BroadTx 广播链上交易

func (*Trans) Check

func (m *Trans) Check() error

Check 检测参数

func (*Trans) Clean

func (m *Trans) Clean()

Clean 清楚交易对象

func (*Trans) NewTx

func (m *Trans) NewTx(exeLimit uint32, execs ...[]byte) (*TX, error)

NewTx 生成交易,不签名,不放入交易池 lt = tx locktime

type TxEvent

type TxEvent struct {
	Idx *BlockIndex
	Blk *BlockInfo //如果交易在块中blk != nil
	Tx  *TX
}

TxEvent 交易发布订阅参数

type TxIn

type TxIn struct {
	OutHash  HASH256 //输出交易hash
	OutIndex VarUInt //对应的输出索引
	Script   Script  //签名后填充脚本
	Sequence VarUInt //连续号
}

TxIn 交易输入

func NewTxIn

func NewTxIn() *TxIn

NewTxIn 创建输入

func (*TxIn) Check

func (in *TxIn) Check(bi *BlockIndex) error

Check 检测输入是否正常

func (TxIn) Clone

func (in TxIn) Clone(seq ...uint) *TxIn

Clone 复制输入

func (*TxIn) Decode

func (in *TxIn) Decode(r IReader) error

Decode 解码交易数据

func (*TxIn) Encode

func (in *TxIn) Encode(w IWriter) error

Encode 编码交易数据

func (*TxIn) ForID

func (in *TxIn) ForID(w IWriter) error

ForID 计算交易id用到的数据

func (TxIn) GetCoin

func (in TxIn) GetCoin(bi *BlockIndex) (*CoinKeyValue, error)

GetCoin 获取引用的coin

func (*TxIn) IsCoinBase

func (in *TxIn) IsCoinBase() bool

IsCoinBase txs的第一个一定是coinbase类型

func (*TxIn) LoadTxOut

func (in *TxIn) LoadTxOut(bi *BlockIndex) (*TxOut, error)

LoadTxOut 获取输入引用的输出

func (TxIn) OutKey

func (in TxIn) OutKey() HASH256

OutKey 获取输入引用key

func (TxIn) SpentKey

func (in TxIn) SpentKey() []byte

SpentKey 消费key,用来记录输入对应的输出是否已被消费

type TxIndex

type TxIndex struct {
	TxID   HASH256
	Height uint32
	Value  TxValue
	// contains filtered or unexported fields
}

TxIndex 用户交易索引

func NewTxIndex

func NewTxIndex(k []byte, v []byte) (*TxIndex, error)

NewTxIndex 从kv数据创建交易索引

func (TxIndex) IsPool

func (ti TxIndex) IsPool() bool

IsPool 是否来自内存

type TxIndexs

type TxIndexs []*TxIndex

TxIndexs 交易索引集合

type TxOut

type TxOut struct {
	Value  Amount //输出金额
	Script Script //锁定脚本
	// contains filtered or unexported fields
}

TxOut 交易输出

func (*TxOut) Check

func (out *TxOut) Check(bi *BlockIndex) error

Check 检测输出是否正常

func (TxOut) Clone

func (out TxOut) Clone() *TxOut

Clone 复制输入

func (*TxOut) Decode

func (out *TxOut) Decode(r IReader) error

Decode 解码输出

func (*TxOut) Encode

func (out *TxOut) Encode(w IWriter) error

Encode 编码输出

func (*TxOut) ForID

func (out *TxOut) ForID(w IWriter) error

ForID 计算交易id用到的数据

func (*TxOut) GetCoin

func (out *TxOut) GetCoin(in *TxIn, bi *BlockIndex) (*CoinKeyValue, error)

GetCoin 获取输入引用的输出 这个输出相关的金额信息

func (*TxOut) HasCoin

func (out *TxOut) HasCoin(in *TxIn, bi *BlockIndex) bool

HasCoin 获取输入引用的输出 输出对应的coin状态是否正常可用

func (TxOut) IsPool

func (out TxOut) IsPool() bool

IsPool 如果来自交易池

type TxPool

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

TxPool 交易池,存放签名成功,未确认的交易 当区块连接后需要把区块中的交易从这个池子删除 交易池加入交易后会记录消费输出,也会记录交易池中可用的金额

func NewTxPool

func NewTxPool() *TxPool

NewTxPool 创建交易池

func (*TxPool) AllTxs

func (pool *TxPool) AllTxs() []*TX

AllTxs 获取所有的tx

func (*TxPool) Close

func (pool *TxPool) Close()

Close 关闭交易池

func (*TxPool) Del

func (pool *TxPool) Del(bi *BlockIndex, id HASH256)

Del 移除交易

func (*TxPool) DelTxs

func (pool *TxPool) DelTxs(bi *BlockIndex, txs []*TX)

DelTxs 当区块打包时,移除多个交易

func (*TxPool) Dump

func (pool *TxPool) Dump(file string) error

Dump 保存数据到文件

func (*TxPool) Get

func (pool *TxPool) Get(id HASH256) (*TX, error)

Get 获取交易

func (*TxPool) GetCoin

func (pool *TxPool) GetCoin(pkh HASH160, txid HASH256, idx VarUInt) (*CoinKeyValue, error)

GetCoin 获取交易相关的金额

func (*TxPool) GetDelTxs

func (pool *TxPool) GetDelTxs(bi *BlockIndex, txs []*TX) []*TX

GetDelTxs 返回已经删除的引用的交易

func (*TxPool) Has

func (pool *TxPool) Has(id HASH256) bool

Has 交易池是否存在某个交易

func (*TxPool) HasCoin

func (pool *TxPool) HasCoin(coin *CoinKeyValue) bool

HasCoin 是否存在可消费的coin

func (*TxPool) IsSpent

func (pool *TxPool) IsSpent(skey []byte) bool

IsSpent 一笔钱是否已经在内存交易池中某个交易消费

func (*TxPool) IsSpentCoin

func (pool *TxPool) IsSpentCoin(coin *CoinKeyValue) bool

IsSpentCoin 一笔钱是否已经在内存交易池中某个交易消费

func (*TxPool) Len

func (pool *TxPool) Len() int

Len 获取交易池交易数量

func (*TxPool) ListCoins

func (pool *TxPool) ListCoins(spkh HASH160) (Coins, error)

ListCoins 获取pkh在交易池中可用的金额 这些金额一般是交易转账找零剩下的金额

func (*TxPool) ListTxsWithID

func (pool *TxPool) ListTxsWithID(bi *BlockIndex, spkh HASH160, limit ...int) (TxIndexs, error)

ListTxsWithID 获取spkh相关的交易

func (*TxPool) Load

func (pool *TxPool) Load(bi *BlockIndex, file string) error

Load 从数据文件加载

func (*TxPool) LoadTxsWithBlk

func (pool *TxPool) LoadTxsWithBlk(bi *BlockIndex, blk *BlockInfo) ([]*TX, error)

LoadTxsWithBlk 取出符合区块blk的交易,大小不能超过限制

func (*TxPool) NewMsgGetTxPool

func (pool *TxPool) NewMsgGetTxPool() *MsgGetTxPool

NewMsgGetTxPool 发送获取交易池所有的交易ID

func (*TxPool) NewMsgTxPool

func (pool *TxPool) NewMsgTxPool(m *MsgGetTxPool) *MsgTxPool

NewMsgTxPool 获取交易池数据,并忽略对方有的交易

func (*TxPool) PushTx

func (pool *TxPool) PushTx(bi *BlockIndex, tx *TX) error

PushTx 添加进去一笔交易放入最后 交易必须是校验过的

func (*TxPool) PushTxs

func (pool *TxPool) PushTxs(bi *BlockIndex, msg *MsgTxPool)

PushTxs 加入其他节点过来的多个交易数据

type TxScript

type TxScript struct {
	Type uint8
	//脚本最大执行时间,时间一半分配给交易脚本,一半分配给签名脚本
	//签名脚本每个输入签名只有 n分之一的一半时间 n为输入数量
	//单位:毫秒
	ExeLimit uint32
	//执行脚本
	Exec VarBytes
}

TxScript 交易脚本

func (*TxScript) Decode

func (ss *TxScript) Decode(r IReader) error

Decode 解码

func (TxScript) Encode

func (ss TxScript) Encode(w IWriter) error

Encode 编码

type TxValue

type TxValue struct {
	//块hash
	BlkID HASH256
	//txs 索引
	TxIdx VarUInt
}

TxValue 存储交易索引值

func (TxValue) Bytes

func (v TxValue) Bytes() ([]byte, error)

Bytes 返回编码二进制数据

func (*TxValue) Decode

func (v *TxValue) Decode(r IReader) error

Decode 解码数据

func (TxValue) Encode

func (v TxValue) Encode(w IWriter) error

Encode 编码数据

func (TxValue) GetTX

func (v TxValue) GetTX(bi *BlockIndex) (*TX, error)

GetTX 获取交易信息

type UINT256

type UINT256 [UInt256Width]uint32

UINT256 unsigned int hash

func NewUINT256

func NewUINT256(v interface{}) UINT256

NewUINT256 创建256位大数

func (UINT256) Add

func (h UINT256) Add(b UINT256) UINT256

Add a = b + c

func (UINT256) Bits

func (h UINT256) Bits() uint

Bits 获取位数

func (UINT256) Cmp

func (h UINT256) Cmp(b UINT256) int

Cmp 比较 >0 = > <0 = < =0 = =

func (UINT256) Compact

func (h UINT256) Compact(negative bool) uint32

Compact Compact

func (UINT256) Div

func (h UINT256) Div(b UINT256) UINT256

Div a = b /c

func (UINT256) Equal

func (h UINT256) Equal(v UINT256) bool

Equal 比较是否相等

func (UINT256) IsZero

func (h UINT256) IsZero() bool

IsZero 是否为空

func (UINT256) Low64

func (h UINT256) Low64() uint64

Low64 获取低位

func (UINT256) Lshift

func (h UINT256) Lshift(shift uint) UINT256

Lshift <<

func (UINT256) Mul

func (h UINT256) Mul(v UINT256) UINT256

Mul c = a * b

func (UINT256) MulUInt32

func (h UINT256) MulUInt32(v uint32) UINT256

MulUInt32 *

func (UINT256) Neg

func (h UINT256) Neg() UINT256

Neg a = ^h

func (UINT256) Rshift

func (h UINT256) Rshift(shift uint) UINT256

Rshift >>

func (*UINT256) SetCompact

func (h *UINT256) SetCompact(c uint32) (bool, bool)

SetCompact return Negative,Overflow

func (*UINT256) SetValue

func (h *UINT256) SetValue(v interface{})

SetValue 设置值

func (UINT256) String

func (h UINT256) String() string

func (UINT256) Sub

func (h UINT256) Sub(b UINT256) UINT256

Sub a = b - c

func (UINT256) ToDouble

func (h UINT256) ToDouble() float64

ToDouble 转位double

func (UINT256) ToHASH256

func (h UINT256) ToHASH256() HASH256

ToHASH256 大数转hash256

type VarBytes

type VarBytes []byte

VarBytes 可变数据定义

func MergeScript

func MergeScript(execs ...[]byte) (VarBytes, error)

MergeScript 合并脚本

func (VarBytes) Compress

func (v VarBytes) Compress(w IWriter) error

Compress 压缩编码数据

func (*VarBytes) Decode

func (v *VarBytes) Decode(r IReader) error

Decode 解码可变数据

func (VarBytes) Encode

func (v VarBytes) Encode(w IWriter) error

Encode 编码可变数据

func (VarBytes) Equal

func (v VarBytes) Equal(b VarBytes) bool

Equal 数据是否相同

func (VarBytes) Len

func (v VarBytes) Len() int

Len 获取数据长度

func (VarBytes) String

func (v VarBytes) String() string

String 转为字符串

func (*VarBytes) Uncompress

func (v *VarBytes) Uncompress(r IReader) error

Uncompress 解压解码解码可变数据

type VarInt

type VarInt int64

VarInt 可变整形

func (*VarInt) Decode

func (v *VarInt) Decode(r IReader) error

Decode 解码可变整形

func (VarInt) Encode

func (v VarInt) Encode(w IWriter) error

Encode 编码可变整形

func (VarInt) ToInt

func (v VarInt) ToInt() int

ToInt 强转位Int类型

type VarUInt

type VarUInt uint64

VarUInt 可变整形(无符号)

func (VarUInt) Bytes

func (v VarUInt) Bytes() []byte

Bytes 获取二进制数据

func (*VarUInt) Decode

func (v *VarUInt) Decode(r IReader) error

Decode 解码

func (VarUInt) Encode

func (v VarUInt) Encode(w IWriter) error

Encode 编码

func (*VarUInt) From

func (v *VarUInt) From(b []byte) int

From 从二进制初始化

func (*VarUInt) SetInt

func (v *VarUInt) SetInt(uv int)

SetInt 使用int初始化

func (*VarUInt) SetUInt32

func (v *VarUInt) SetUInt32(uv uint32)

SetUInt32 使用uint32初始化

func (VarUInt) SortBytes

func (v VarUInt) SortBytes() []byte

func (VarUInt) ToAmount

func (v VarUInt) ToAmount() Amount

ToAmount 强转为金额类型

func (VarUInt) ToInt

func (v VarUInt) ToInt() int

ToInt 强转为Int类型

func (VarUInt) ToUInt32

func (v VarUInt) ToUInt32() uint32

ToUInt32 强转为无符号32位整形

type WitnessScript

type WitnessScript struct {
	Type uint8      //SCRIPT_WITNESS_TYPE
	Num  uint8      //签名数量
	Less uint8      //至少正确的数量
	Arb  uint8      //是否启用仲裁
	Pks  []PKBytes  //公钥
	Sig  []SigBytes //签名
	Exec VarBytes   //执行脚本
}

WitnessScript 隔离见证脚本

func (WitnessScript) Address

func (ss WitnessScript) Address() Address

Address 获取地址

func (WitnessScript) Check

func (ss WitnessScript) Check() error

Check 检查签名证书数量

func (WitnessScript) CheckSigs

func (ss WitnessScript) CheckSigs(sigs []SigBytes) error

CheckSigs 检查指定的签名

func (*WitnessScript) Decode

func (ss *WitnessScript) Decode(r IReader) error

Decode 解码

func (WitnessScript) Encode

func (ss WitnessScript) Encode(w IWriter) error

Encode 编码

func (*WitnessScript) Final

func (ss *WitnessScript) Final() (Script, error)

FinalScript 完成脚本,检查并精简脚本,签名完成之后调用

func (WitnessScript) ForID

func (ss WitnessScript) ForID(w IWriter) error

ForID id计算

func (WitnessScript) Hash

func (ss WitnessScript) Hash() (HASH160, error)

Hash 结算hash

func (WitnessScript) IsEnableArb

func (ss WitnessScript) IsEnableArb() bool

IsEnableArb 是否启用仲裁

func (WitnessScript) ToAccount

func (ss WitnessScript) ToAccount() (*Account, error)

ToAccount 转换为账户信息

func (WitnessScript) ToScript

func (ss WitnessScript) ToScript() (Script, error)

ToScript 转换为脚本存储

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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