gobbc

package module
v1.0.20 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2020 License: BSD-3-Clause Imports: 24 Imported by: 1

README

BBC 签名库 in go

修改自: https://github.com/bigbangcore/OffLineSignLib

多签部分参考core代码实现

TODO

  • 增加更多的测试用例
  • 增加持续集成测试
  • 代码审计

To 开发人员

Bigbang 的release notes不够详细,不能依靠release notes判断改动,在升级新包的时候务必执行完整的集成测试

  • 当前目录下 go test
  • qa 目录下 go test

增加新的特性也务必确保测试用例的覆盖率,至少需要确保核心功能可以正常使用

测试:make test 集成测试:make qaTest all: make all

Features

  • 生成密钥对、地址
  • 交易序列化和解析
  • 使用私钥签名
  • 多签地址交易签名

数据格式

  • 可读私钥, seed 反转后hex编码
  • 可读公钥, 公钥反转后hex编码
  • 可读地址, 公钥base32编码 + crc24q校验位

Missing features

  • 部分模版地址签名支持

其他

开发过程中的一些小插曲参考 doc 目录

Documentation

Index

Constants

View Source
const (
	PubkeyHexLen     = 32*2 + 1
	PrivkeyHexLen    = 32*2 + 1
	PubkeyAddressLen = 57 + 1
	Uint256HexLen    = 65

	AddressPrefixPubk = '1'
	AddressPrefixTpl  = '2'

	PrefixPubk     = 1
	PrefixTemplate = 2
)

some len const

View Source
const (
	TemplateTypeMin TemplateType = iota
	TemplateTypeWeighted
	TemplateTypeMultisig //多重签名
	TemplateTypeFork
	TemplateTypeProof    //pow
	TemplateTypeDelegate //dpos
	TemplateTypeExchange
	TemplateTypeVote //dpos投票
	TemplateTypePayment
	TemplateTypeMax

	TemplateTypeMultisigPrefix = "02" //2 little endian

	// https://github.com/BigBang-Foundation/BigBang/wiki/通用Tx-vchData系列化定义
	// DataSzDescNone 表示没有strDescription
	DataSzDescNone uint8 = 0
)

模版类型

View Source
const Precision = 1000000
View Source
const TemplateDataSpliter = ","

TemplateDataSpliter 使用,分隔多个template data

Variables

View Source
var Debug bool

Functions

func Base32Encode

func Base32Encode(md32 []uint8) string

Base32Encode copied from c++

func ConvertAddress2pubk

func ConvertAddress2pubk(address string) (string, error)

ConvertAddress2pubk .

func CopyReverse

func CopyReverse(bs []byte) []byte

CopyReverse copy and reverse []byte

func CopyReverseThenEncodeHex

func CopyReverseThenEncodeHex(bs []byte) string

CopyReverseThenEncodeHex 复制[]byte,反转后hex.EncodeToString

func CreateTemplateDataDexOrder added in v1.0.11

func CreateTemplateDataDexOrder(p DexOrderParam) (string, string, error)

CreateTemplateDataDexOrder return tplID, tplData, error

func CryptoMultiSign

func CryptoMultiSign(pubks [][]byte, privk ed25519.PrivateKey, msg []byte, currentSig []byte) ([]byte, error)

CryptoMultiSign pubks 公钥数组,privk 私钥, msg 待签名数据, sig 已有签名 签名结构参考:https://github.com/bigbangcore/BigBang/wiki/%E5%A4%9A%E9%87%8D%E7%AD%BE%E5%90%8D#%E7%AD%BE%E5%90%8D

index                     R1           S1              Rn            Sn

signature: |_________________________________|____________|____________|...|____________|____________|

(keys-length - 1) / 8 + 1 bytes    32 bytes     32 bytes         32 bytes      32 bytes

func EncodeAddress

func EncodeAddress(prefix uint8, hexed string) (string, error)

EncodeAddress Get Address hex string from public key hex string

func GetAddressBytes added in v1.0.11

func GetAddressBytes(add string) (byte, []byte, error)

GetAddressBytes prefix, pubkOrHash, error

func GetPubKeyAddress

func GetPubKeyAddress(pubk string) (string, error)

GetPubKeyAddress Get Address hex string from public key hex string

func JSONIndent

func JSONIndent(v interface{}) string

JSONIndent pretty json

func ParsePrivkHex

func ParsePrivkHex(privkHex string) (ed25519.PrivateKey, error)

ParsePrivkHex BBC 私钥解析为ed25519.PrivateKey

func ParsePublicKeyHex

func ParsePublicKeyHex(hexedPubK string) ([]byte, error)

ParsePublicKeyHex 解析私钥为实际使用的seed

func PrivateKeyHex2Seed

func PrivateKeyHex2Seed(hexedPrivk string) ([]byte, error)

PrivateKeyHex2Seed 解析私钥为实际使用的seed

func Seed2pubk

func Seed2pubk(seed []byte) ([]byte, error)

Seed2pubk .

func Seed2pubkString

func Seed2pubkString(seed []byte) (string, error)

Seed2pubkString .

func Seed2string

func Seed2string(seed []byte) string

Seed2string 私钥字符串

func UntilError

func UntilError(fns ...func() error) error

UntilError execute all func until error returned

func UtilDataEncoding

func UtilDataEncoding(data []byte) (string, error)

UtilDataEncoding 将tx data 进行编码

Types

type AddrKeyPair

type AddrKeyPair struct {
	Addr  string
	Privk string
	Pubk  string
}

AddrKeyPair 地址、私钥、公钥

func MakeKeyPair

func MakeKeyPair() (AddrKeyPair, error)

MakeKeyPair .

type Address added in v1.0.11

type Address string

type CDestination added in v1.0.16

type CDestination struct {
	Prefix uint8
	Data   [32]byte
}

func NewCDestinationFromAddress added in v1.0.19

func NewCDestinationFromAddress(address string) (cd CDestination, err error)

NewCDestinationFromAddress 可以用来校验地址,或者获取原始地址字节

func NewCDestinationFromHexString added in v1.0.19

func NewCDestinationFromHexString(s string) (cd CDestination, err error)

func (CDestination) String added in v1.0.16

func (a CDestination) String() string

type DexOrderParam added in v1.0.11

type DexOrderParam struct {
	SellerAddress Address `json:"seller_address"`
	Coinpair      string  `json:"coinpair"`
	Price         int64   `json:"price"`
	Fee           int32   `json:"fee"`
	RecvAddress   string  `json:"recv_address"`
	ValidHeight   int32   `json:"valid_height"`
	MatchAddress  Address `json:"match_address"`
	DealAddress   string  `json:"deal_address"`
	Timestamp     uint32  `json:"timestamp"`
}

DexOrderParam .

type MultisigInfo

type MultisigInfo struct {
	Hex     string
	M, N    uint8 //m-n签名,N名成员需要至少M个签名
	Members []MultisigMember
}

MultisigInfo 多签信息

func ParseMultisigTemplateHex

func ParseMultisigTemplateHex(hexData string) (*MultisigInfo, error)

ParseMultisigTemplateHex 解析多签地址hex, hex decode 前2byte代表类型,通常是0200 (不确定是0200或者0020) 接下来1+8 byte为M,N 接下来有N个33 (32为公钥,1为weight) ref to: https://github.com/bigbangcore/BigBang/wiki/%E5%A4%9A%E9%87%8D%E7%AD%BE%E5%90%8D |---2---|---1---|---8---|---33*n---| | type | M | N | keys... |

func (MultisigInfo) Pubks

func (mi MultisigInfo) Pubks() [][]byte

Pubks 参与签名的公钥列表

func (MultisigInfo) SignTemplatePart

func (mi MultisigInfo) SignTemplatePart() []byte

SignTemplatePart 签名时签名的前半部分

type MultisigMember

type MultisigMember struct {
	Pub    []byte
	Weight uint8
}

MultisigMember .

type RawTransaction

type RawTransaction struct {
	Version         uint16
	Typ             uint16 //type > typ
	Timestamp       uint32
	LockUntil       uint32
	HashAnchorBytes [32]byte `json:"-"` // fork id
	SizeIn          uint64   //input 数量
	Input           []byte   `json:"-"`
	Prefix          uint8    //addr prefix
	AddressBytes    [32]byte `json:"-"` // binary data (caller do not care about this field, you just care hex field)
	Amount          int64
	TxFee           int64
	SizeOut         uint64
	VchData         []byte `json:"-"` // binary (caller do not care about this field, you just care hex field)
	SizeSign        uint64 // binary sign data size, ref: https://github.com/bigbangcore/BigBang/wiki/IO-Stream#stdvector-stdmap-stdstring
	SignBytes       []byte `json:"-"` // [template data]sig
}

RawTransaction 实际的序列话数据结构 注意:数据类型不要更改(序列化时对类型有依赖)

func (*RawTransaction) Encode

func (rtx *RawTransaction) Encode(serializer Serializer, encodeSignData bool) (string, error)

Encode .

func (*RawTransaction) EncodeBytes

func (rtx *RawTransaction) EncodeBytes(serializer Serializer, encodeSignData bool) ([]byte, error)

EncodeBytes .

func (*RawTransaction) SignWithPrivateKey

func (rtx *RawTransaction) SignWithPrivateKey(serializer Serializer, templateDataList, privkHex string) error

SignWithPrivateKey 用私钥签名 templateDataList: 使用[,]分隔的模版数据列表, - 对于不需要模版数据的交易传入空字符串即可, - 如果传入了模版数据签名后会将模版数据按照顺序放在签名前面, - 如果传入的模版数据检测到多重签名则在签名时使用多重签名机制

通常,在from为模版地址时需要传入from的模版数据,可以通过rpc validateaddress 获取(data.addressdata.templatedata.hex) 当to地址为vote类型模版地址时需要传入to地址模版数据 特别的,只有1种情况需要传入2个模版地址:delegate类型模版的owner为多签地址,从该地址转出时需要传入:delegate模版数据,多签模版数据 (基于上面一种情况,如果转出地址为vote template可能还需要提供vote template data, 一共3个😂,这个未经测试、验证)

下面列出常见的场景: 一般公钥地址转出(到非vote template)->(不需要模版数据) 一般公钥地址投票时->投票模版数据 一般公钥投票赎回时->投票模版数据 多签地址签名(转账到一般地址)->多签模版数据 从dpos委托模版地址转出->委托模版数据 从dpos委托模版(owner为多签)地址转出->委托模版数据+多签模版数据 从pow挖矿模版地址转出->pow挖矿模版地址

注意:签名逻辑不对模版数据进行严格合理的校验,因为离线环境下无法感知模版数据的有效性,调用方需自行确保参数正确

func (RawTransaction) ToTransaction

func (rtx RawTransaction) ToTransaction(includeSignData bool) Transaction

ToTransaction .

func (*RawTransaction) TxHash

func (rtx *RawTransaction) TxHash(serializer Serializer) ([32]byte, error)

TxHash 计算tx hash, tx hash用于签名,签名本质上对txHash 进行ed25519签名

func (*RawTransaction) Txid

func (rtx *RawTransaction) Txid(serializer Serializer) (string, error)

Txid serialize tx -> blake2bSum256 -> reverse(got x) -> replace [0:4] with timestamp(bigEndian) -> hex encode

type Serializer

type Serializer interface {
	Serialize(RawTransaction) ([]byte, error)
	Deserialize([]byte) (RawTransaction, error)
}

Serializer tx Serializer

var BBCSerializer Serializer = serializer{/* contains filtered or unexported fields */}
var MKFSerializer Serializer = serializer{/* contains filtered or unexported fields */}

type TW

type TW struct {
	*testing.T
	// contains filtered or unexported fields
}

TW testing.T wrap

func (*TW) Continue

func (tw *TW) Continue(_continue bool) *TW

Continue 断言失败时是否继续测试(不执行FailNow)

func (*TW) Copy

func (tw *TW) Copy() *TW

Copy .

func (*TW) Equal

func (tw *TW) Equal(expected, actual interface{}, args ...interface{}) *TW

Equal reflect.DeepEqual

func (*TW) IsZero

func (tw *TW) IsZero(v interface{}, args ...interface{}) *TW

IsZero if flag == false, fatal

func (*TW) Nil

func (tw *TW) Nil(x interface{}, args ...interface{}) *TW

Nil if x not nil, fatal

func (*TW) NotZero

func (tw *TW) NotZero(v interface{}, args ...interface{}) *TW

NotZero if flag == false, fatal

func (*TW) True

func (tw *TW) True(flag bool, args ...interface{}) *TW

True if flag == false, fatal

type TXBuilder

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

TXBuilder .

func NewTXBuilder

func NewTXBuilder() *TXBuilder

func (*TXBuilder) AddInput

func (b *TXBuilder) AddInput(txid string, vout uint8) *TXBuilder

AddInput 参考listunspent,确保输入金额满足amount

func (*TXBuilder) Build

func (b *TXBuilder) Build() (*RawTransaction, error)

Build .

func (*TXBuilder) SetAddress

func (b *TXBuilder) SetAddress(add string) *TXBuilder

SetAddress 转账地址

func (*TXBuilder) SetAmount

func (b *TXBuilder) SetAmount(amount float64) *TXBuilder

SetAmount 转账金额

func (*TXBuilder) SetAnchor

func (b *TXBuilder) SetAnchor(anchor string) *TXBuilder

SetAnchor 锚定分支id

func (*TXBuilder) SetData

func (b *TXBuilder) SetData(dataFmt string, data []byte) *TXBuilder

SetData 自动编码数据,自动生成uuid和时间戳,不带格式描述

func (*TXBuilder) SetDataWith added in v1.0.17

func (b *TXBuilder) SetDataWith(_uuid string, timestamp int64, dataFmt string, data []byte) *TXBuilder

SetDataWith 指定uuid,timestamp,data

func (*TXBuilder) SetErr added in v1.0.18

func (b *TXBuilder) SetErr(e error)

return b.err != nil

func (*TXBuilder) SetFee

func (b *TXBuilder) SetFee(fee float64) *TXBuilder

SetFee 手续费,目前0.01,如果带data则0.03, 额外需咨询BBC

func (*TXBuilder) SetLockUntil

func (b *TXBuilder) SetLockUntil(lockUntil int) *TXBuilder

SetLockUntil lock until

func (*TXBuilder) SetRawData added in v1.0.17

func (b *TXBuilder) SetRawData(data []byte) *TXBuilder

SetRawData https://github.com/BigBang-Foundation/BigBang/wiki/通用Tx-vchData系列化定义, 原始data设置,不自动填充任何数据(不自动提供uuid time format数据)

func (*TXBuilder) SetTimestamp

func (b *TXBuilder) SetTimestamp(timestamp int) *TXBuilder

SetTimestamp 当前时间戳

func (*TXBuilder) SetType added in v1.0.10

func (b *TXBuilder) SetType(v int) *TXBuilder

SetType tx type

func (*TXBuilder) SetVersion

func (b *TXBuilder) SetVersion(v int) *TXBuilder

SetVersion 当前版本 1

type TXData

type TXData struct {
	TplHex string `json:"tpl_hex,omitempty"` //成员信息,通过rpc validateaddress (多签模版地址) 取到的值的ret.Addressdata.Templatedata.Hex
	TxHex  string `json:"tx_hex,omitempty"`  //encoded tx data
}

TXData 包含了原始交易数据和需要的模版数据,模版数据使用,(英文逗号)分隔

func (*TXData) ContainsMultisig added in v1.0.13

func (data *TXData) ContainsMultisig() bool

ContainsMultisig .

func (*TXData) DecodeString

func (data *TXData) DecodeString(jsonHex string) error

DecodeString parse jsonHex set value to data

func (*TXData) EncodeString

func (data *TXData) EncodeString() (string, error)

EncodeString json marshal + hex encode

type TemplateType

type TemplateType int16

TemplateType 模版类型

func GetTemplateType

func GetTemplateType(templateData string) TemplateType

GetTemplateType 如果解析失败则返回TemplateTypeMin(0)

func (TemplateType) String

func (typ TemplateType) String() string

type Transaction

type Transaction struct {
	RawTransaction
	HashAnchor string // hex string([65]byte)
	Address    string // hex string ([64 + 1]byte)
	Sign       string // hex string
	Vin        []Vin
	Data       string
}

Transaction . TODO 增加vout

func DecodeRawTransaction

func DecodeRawTransaction(serializer Serializer, txData string, decodeSignData bool) (*Transaction, error)

DecodeRawTransaction hexed tx parse

type VchData added in v1.0.17

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

VchData https://github.com/BigBang-Foundation/BigBang/wiki/通用Tx-VchData系列化定义

func NewVchData added in v1.0.17

func NewVchData(dataFmtDesc string, data []byte) (VchData, error)

NewVchData . dataFmtDesc: eg,JSON BSON MsgPack (为空时表示没有格式)

func NewVchDataWith added in v1.0.17

func NewVchDataWith(uuid uuid.UUID, time time.Time, dataFmtDesc string, data []byte) (VchData, error)

NewVchDataWith with uuid time

func ParseVchData added in v1.0.17

func ParseVchData(raw []byte) (*VchData, error)

func (VchData) Bytes added in v1.0.17

func (vd VchData) Bytes() []byte

func (VchData) Data added in v1.0.17

func (vd VchData) Data() []byte

func (VchData) DataFmtDesc added in v1.0.17

func (vd VchData) DataFmtDesc() (string, error)

func (VchData) RawDataFmtDesc added in v1.0.17

func (vd VchData) RawDataFmtDesc() []byte

func (VchData) Time added in v1.0.17

func (vd VchData) Time() time.Time

func (VchData) UUID added in v1.0.17

func (vd VchData) UUID() uuid.UUID

type Vin

type Vin struct {
	Txid string
	Vout int
}

type VoteTpl added in v1.0.16

type VoteTpl struct {
	Delegate CDestination
	Voter    CDestination
}

Jump to

Keyboard shortcuts

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