tokens

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2021 License: GPL-3.0 Imports: 14 Imported by: 5

README

How to add bridge support of new blockchain

1. create a new directory for each block chain

for example, btc, eth, fsn etc.

2. implement methods in CrossChainBridge interface

IsSrcEndpoint() bool

IsSrcEndpoint returns true if this bridge is on the source block chain, otherwise returns false.


SetChainAndGateway(*ChainConfig, *GatewayConfig)

SetChainAndGateway set chain and gateway config.


GetChainConfig() *ChainConfig

GetChainConfig get chain config.


GetGatewayConfig() *GatewayConfig

GetGatewayConfig get gateway config.


GetTokenConfig(pairID string) *TokenConfig

GetTokenConfig get token config.


VerifyTokenConfig(*TokenConfig) error

VerifyTokenConfig verify token config.


IsValidAddress(address string) bool

IsValidAddress check if given address is valid.


GetTransaction(txHash string) (interface{}, error)

GetTransaction get transaction by hash.


GetTransactionStatus(txHash string) *TxStatus

GetTransactionStatus get transaction status by hash.


VerifyTransaction(pairID, txHash string, allowUnstable bool) (*TxSwapInfo, error)

VerifyTransaction verify transaction by hash.


VerifyMsgHash(rawTx interface{}, msgHash []string) error

VerifyMsgHash verify message hash of rawtx in DCRM signing.


BuildRawTransaction(args *BuildTxArgs) (rawTx interface{}, err error)

BuildRawTransaction build raw transaction for swapin/swapout.


SignTransaction(rawTx interface{}, pairID string) (signedTx interface{}, txHash string, err error)

SignTransaction sign transaction with configed private key.


DcrmSignTransaction(rawTx interface{}, args *BuildTxArgs) (signedTx interface{}, txHash string, err error)

DcrmSignTransaction sign transaction in DCRM way.


SendTransaction(signedTx interface{}) (txHash string, err error)

SendTransaction send/broadcast signed transaction.


GetLatestBlockNumber() (uint64, error)

GetLatestBlockNumber get the latest block number.


GetLatestBlockNumberOf(apiAddress string) (uint64, error)

GetLatestBlockNumberOf get the latest block number by connecting to specified full node RPC address.


StartChainTransactionScanJob()

StartChainTransactionScanJob start scan chain transaction and auto register found swapin or swapout of this bridge.


StartPoolTransactionScanJob()

StartPoolTransactionScanJob start scan pool transaction and auto register found swapin or swapout of this bridge.


GetBalance(accountAddress string) (*big.Int, error)

GetBalance get coin balance of given account address.


GetTokenBalance(tokenType, tokenAddress, accountAddress string) (*big.Int, error)

GetTokenBalance get token balance of given token and account.


GetTokenSupply(tokenType, tokenAddress string) (*big.Int, error)

GetTokenSupply get token total supply of give token.


3. other possible way

Because some chain are forked from already implemented blockchain, we can derive from this implemented bridge and update some interface implement.

For example, fsn is forked from eth. So we derive fsn bridge from eth bridge and update some chain verify, and then fsn is also supported now as it has implememted all the required methods in CrossChainBridge interface.

Documentation

Index

Constants

View Source
const (
	LockMemoPrefix   = "SWAPTO:"
	UnlockMemoPrefix = "SWAPTX:"
	AggregateMemo    = "aggregate"
)

transaction memo prefix

Variables

View Source
var (
	AggregateIdentifier = "aggregate"

	SrcBridge CrossChainBridge
	DstBridge CrossChainBridge

	SrcLatestBlockHeight uint64
	DstLatestBlockHeight uint64

	IsDcrmDisabled bool
)

common variables

View Source
var (
	ErrSwapTypeNotSupported          = errors.New("swap type not supported in this endpoint")
	ErrBridgeSourceNotSupported      = errors.New("bridge source not supported")
	ErrBridgeDestinationNotSupported = errors.New("bridge destination not supported")
	ErrUnknownSwapType               = errors.New("unknown swap type")
	ErrMsgHashMismatch               = errors.New("message hash mismatch")
	ErrWrongCountOfMsgHashes         = errors.New("wrong count of msg hashed")
	ErrWrongRawTx                    = errors.New("wrong raw tx")
	ErrWrongExtraArgs                = errors.New("wrong extra args")
	ErrNoBtcBridge                   = errors.New("no btc bridge exist")
	ErrWrongSwapinTxType             = errors.New("wrong swapin tx type")
	ErrBuildSwapTxInWrongEndpoint    = errors.New("build swap in/out tx in wrong endpoint")
	ErrTxBeforeInitialHeight         = errors.New("transaction before initial block height")
	ErrAddressIsInBlacklist          = errors.New("address is in black list")

	ErrTodo = errors.New("developing: TODO")

	ErrTxNotFound           = errors.New("tx not found")
	ErrTxNotStable          = errors.New("tx not stable")
	ErrTxWithWrongReceiver  = errors.New("tx with wrong receiver")
	ErrTxWithWrongContract  = errors.New("tx with wrong contract")
	ErrTxWithWrongInput     = errors.New("tx with wrong input data")
	ErrTxWithWrongLogData   = errors.New("tx with wrong log data")
	ErrTxIsAggregateTx      = errors.New("tx is aggregate tx")
	ErrWrongP2shBindAddress = errors.New("wrong p2sh bind address")
	ErrTxFuncHashMismatch   = errors.New("tx func hash mismatch")
	ErrDepositLogNotFound   = errors.New("deposit log not found or removed")
	ErrSwapoutLogNotFound   = errors.New("swapout log not found or removed")
	ErrUnknownPairID        = errors.New("unknown pair ID")
	ErrBindAddressMismatch  = errors.New("bind address mismatch")

	// errors should register
	ErrTxWithWrongMemo       = errors.New("tx with wrong memo")
	ErrTxWithWrongValue      = errors.New("tx with wrong value")
	ErrTxWithWrongReceipt    = errors.New("tx with wrong receipt")
	ErrTxWithWrongSender     = errors.New("tx with wrong sender")
	ErrTxSenderNotRegistered = errors.New("tx sender not registered")
	ErrTxIncompatible        = errors.New("tx incompatible")
	ErrBindAddrIsContract    = errors.New("bind address is contract")
	ErrRPCQueryError         = errors.New("rpc query error")
)

common errors

Functions

func CalcSwappedValue

func CalcSwappedValue(pairID string, value *big.Int, isSrc bool) *big.Int

CalcSwappedValue calc swapped value (get rid of fee)

func CheckSwapValue

func CheckSwapValue(pairID string, value *big.Int, isSrc bool) bool

CheckSwapValue check swap value is in right range

func FromBits

func FromBits(value *big.Int, decimals uint8) float64

FromBits convert from bits

func GetAllPairIDs added in v0.3.0

func GetAllPairIDs() []string

GetAllPairIDs get all pairIDs

func GetBigValueThreshold

func GetBigValueThreshold(pairID string, isSrc bool) *big.Int

GetBigValueThreshold get big value threshold

func GetTokenPairsConfig added in v0.3.0

func GetTokenPairsConfig() map[string]*TokenPairConfig

GetTokenPairsConfig get token pairs config

func GetTokenPairsDir added in v0.3.0

func GetTokenPairsDir() string

GetTokenPairsDir get token pairs directory

func IsTokenPairExist added in v0.3.0

func IsTokenPairExist(pairID string) bool

IsTokenPairExist is token pair exist

func LoadTokenPairsConfig added in v0.3.0

func LoadTokenPairsConfig(check bool)

LoadTokenPairsConfig load token pairs config

func LoadTokenPairsConfigInDir added in v0.3.0

func LoadTokenPairsConfigInDir(dir string, check bool) (map[string]*TokenPairConfig, error)

LoadTokenPairsConfigInDir load token pairs config

func SetLatestBlockHeight

func SetLatestBlockHeight(latest uint64, isSrc bool)

SetLatestBlockHeight set latest block height

func SetTokenPairsConfig added in v0.3.0

func SetTokenPairsConfig(pairsConfig map[string]*TokenPairConfig, check bool)

SetTokenPairsConfig set token pairs config

func SetTokenPairsDir added in v0.3.0

func SetTokenPairsDir(dir string)

SetTokenPairsDir set token pairs directory

func ShouldRegisterSwapForError

func ShouldRegisterSwapForError(err error) bool

ShouldRegisterSwapForError return true if this error should record in database

func ToBits

func ToBits(value float64, decimals uint8) *big.Int

ToBits convert to bits

Types

type AllExtras

type AllExtras struct {
	BtcExtra *BtcExtraArgs `json:"btcExtra,omitempty"`
	EthExtra *EthExtraArgs `json:"ethExtra,omitempty"`
}

AllExtras struct

type BlockExtraArgs added in v0.3.1

type BlockExtraArgs struct {
	CoreAPIs         []BlocknetCoreAPIArgs
	UTXOAPIAddresses []string
}

BlockExtraArgs struct

type BlocknetCoreAPIArgs added in v0.3.1

type BlocknetCoreAPIArgs struct {
	APIAddress  string
	RPCUser     string
	RPCPassword string
	DisableTLS  bool
}

BlocknetCoreAPIArgs struct

type BtcExtraArgs

type BtcExtraArgs struct {
	RelayFeePerKb     *int64         `json:"relayFeePerKb,omitempty"`
	ChangeAddress     *string        `json:"-"`
	PreviousOutPoints []*BtcOutPoint `json:"previousOutPoints,omitempty"`
}

BtcExtraArgs struct

type BtcExtraConfig

type BtcExtraConfig struct {
	MinRelayFee       int64
	MinRelayFeePerKb  int64
	MaxRelayFeePerKb  int64
	PlusFeePercentage uint64
	EstimateFeeBlocks int

	UtxoAggregateMinCount  int
	UtxoAggregateMinValue  uint64
	UtxoAggregateToAddress string
}

BtcExtraConfig used to build swpout to btc tx

type BtcOutPoint

type BtcOutPoint struct {
	Hash  string `json:"hash"`
	Index uint32 `json:"index"`
}

BtcOutPoint struct

type BuildTxArgs

type BuildTxArgs struct {
	SwapInfo    `json:"swapInfo,omitempty"`
	From        string     `json:"from,omitempty"`
	To          string     `json:"to,omitempty"`
	Value       *big.Int   `json:"value,omitempty"`
	OriginValue *big.Int   `json:"originValue,omitempty"`
	Memo        string     `json:"memo,omitempty"`
	Input       *[]byte    `json:"input,omitempty"`
	Extra       *AllExtras `json:"extra,omitempty"`
}

BuildTxArgs struct

func (*BuildTxArgs) GetExtraArgs

func (args *BuildTxArgs) GetExtraArgs() *BuildTxArgs

GetExtraArgs get extra args

func (*BuildTxArgs) GetTxNonce

func (args *BuildTxArgs) GetTxNonce() uint64

GetTxNonce get tx nonce

type ChainConfig added in v0.3.0

type ChainConfig struct {
	BlockChain     string
	NetID          string
	Confirmations  *uint64
	InitialHeight  *uint64
	EnableScan     bool
	EnableScanPool bool
	ScanReceipt    bool `json:",omitempty"`

	MaxGasPriceFluctPercent uint64 `json:",omitempty"`
	WaitTimeToReplace       int64  // seconds
	MaxReplaceCount         int
	EnableReplaceSwap       bool
}

ChainConfig struct

func (*ChainConfig) CheckConfig added in v0.3.0

func (c *ChainConfig) CheckConfig() error

CheckConfig check chain config

type CrossChainBridge

type CrossChainBridge interface {
	IsSrcEndpoint() bool

	SetChainAndGateway(*ChainConfig, *GatewayConfig)

	GetChainConfig() *ChainConfig
	GetGatewayConfig() *GatewayConfig
	GetTokenConfig(pairID string) *TokenConfig

	VerifyTokenConfig(*TokenConfig) error
	IsValidAddress(address string) bool

	GetTransaction(txHash string) (interface{}, error)
	GetTransactionStatus(txHash string) *TxStatus
	VerifyTransaction(pairID, txHash string, allowUnstable bool) (*TxSwapInfo, error)
	VerifyMsgHash(rawTx interface{}, msgHash []string) error

	BuildRawTransaction(args *BuildTxArgs) (rawTx interface{}, err error)
	SignTransaction(rawTx interface{}, pairID string) (signedTx interface{}, txHash string, err error)
	DcrmSignTransaction(rawTx interface{}, args *BuildTxArgs) (signedTx interface{}, txHash string, err error)
	SendTransaction(signedTx interface{}) (txHash string, err error)

	GetLatestBlockNumber() (uint64, error)
	GetLatestBlockNumberOf(apiAddress string) (uint64, error)

	StartChainTransactionScanJob()
	StartPoolTransactionScanJob()

	GetBalance(accountAddress string) (*big.Int, error)
	GetTokenBalance(tokenType, tokenAddress, accountAddress string) (*big.Int, error)
	GetTokenSupply(tokenType, tokenAddress string) (*big.Int, error)
}

CrossChainBridge interface

func GetCrossChainBridge

func GetCrossChainBridge(isSrc bool) CrossChainBridge

GetCrossChainBridge get bridge of specified endpoint

type CrossChainBridgeBase

type CrossChainBridgeBase struct {
	ChainConfig   *ChainConfig
	GatewayConfig *GatewayConfig
	IsSrc         bool
}

CrossChainBridgeBase base bridge

func NewCrossChainBridgeBase

func NewCrossChainBridgeBase(isSrc bool) *CrossChainBridgeBase

NewCrossChainBridgeBase new base bridge

func (*CrossChainBridgeBase) GetChainConfig added in v0.3.0

func (b *CrossChainBridgeBase) GetChainConfig() *ChainConfig

GetChainConfig get chain config

func (*CrossChainBridgeBase) GetDcrmPublicKey added in v0.3.0

func (b *CrossChainBridgeBase) GetDcrmPublicKey(pairID string) string

GetDcrmPublicKey get dcrm address's public key

func (*CrossChainBridgeBase) GetGatewayConfig added in v0.3.0

func (b *CrossChainBridgeBase) GetGatewayConfig() *GatewayConfig

GetGatewayConfig get gateway config

func (*CrossChainBridgeBase) GetTokenConfig added in v0.3.0

func (b *CrossChainBridgeBase) GetTokenConfig(pairID string) *TokenConfig

GetTokenConfig get token config

func (*CrossChainBridgeBase) IsSrcEndpoint

func (b *CrossChainBridgeBase) IsSrcEndpoint() bool

IsSrcEndpoint returns if bridge is at the source endpoint

func (*CrossChainBridgeBase) SetChainAndGateway added in v0.3.0

func (b *CrossChainBridgeBase) SetChainAndGateway(chainCfg *ChainConfig, gatewayCfg *GatewayConfig)

SetChainAndGateway set chain and gateway config

type EthExtraArgs

type EthExtraArgs struct {
	Gas      *uint64  `json:"gas,omitempty"`
	GasPrice *big.Int `json:"gasPrice,omitempty"`
	Nonce    *uint64  `json:"nonce,omitempty"`
}

EthExtraArgs struct

type GatewayConfig

type GatewayConfig struct {
	APIAddress    []string
	APIAddressExt []string
	Extras        *GatewayExtras
}

GatewayConfig struct

type GatewayExtras added in v0.3.1

type GatewayExtras struct {
	BlockExtra *BlockExtraArgs
}

GatewayExtras struct

type NonceSetter

type NonceSetter interface {
	IsTransactionOnChain(txHash string) bool
	GetPoolNonce(address, height string) (uint64, error)
	SetNonce(pairID string, value uint64)
	AdjustNonce(pairID string, value uint64) (nonce uint64)
	IncreaseNonce(pairID string, value uint64)
}

NonceSetter interface (for eth-like)

type P2shAddressInfo

type P2shAddressInfo struct {
	BindAddress        string
	P2shAddress        string
	RedeemScript       string
	RedeemScriptDisasm string
}

P2shAddressInfo struct

type SwapInfo

type SwapInfo struct {
	PairID     string     `json:"pairid,omitempty"`
	SwapID     string     `json:"swapid,omitempty"`
	SwapType   SwapType   `json:"swaptype,omitempty"`
	TxType     SwapTxType `json:"txtype,omitempty"`
	Bind       string     `json:"bind,omitempty"`
	Identifier string     `json:"identifier,omitempty"`
}

SwapInfo struct

type SwapTxType

type SwapTxType uint32

SwapTxType type

const (
	SwapinTx     SwapTxType = iota // 0
	SwapoutTx                      // 1
	P2shSwapinTx                   // 2
)

SwapTxType constants

func (SwapTxType) String

func (s SwapTxType) String() string

type SwapType

type SwapType uint32

SwapType type

const (
	NoSwapType SwapType = iota
	SwapinType
	SwapoutType
)

SwapType constants

func (SwapType) String

func (s SwapType) String() string

type TokenConfig

type TokenConfig struct {
	ID                     string `json:",omitempty"`
	Name                   string
	Symbol                 string
	Decimals               *uint8
	Description            string `json:",omitempty"`
	DepositAddress         string `json:",omitempty"`
	DcrmAddress            string
	DcrmPubkey             string   `json:"-"`
	ContractAddress        string   `json:",omitempty"`
	ContractCodeHash       string   `json:",omitempty"`
	MaximumSwap            *float64 // whole unit (eg. BTC, ETH, FSN), not Satoshi
	MinimumSwap            *float64 // whole unit
	BigValueThreshold      *float64
	SwapFeeRate            *float64
	MaximumSwapFee         *float64
	MinimumSwapFee         *float64
	PlusGasPricePercentage uint64 `json:",omitempty"`
	DisableSwap            bool
	IsDelegateContract     bool
	DelegateToken          string `json:",omitempty"`

	DefaultGasLimit uint64 `json:",omitempty"`

	// use private key address instead
	DcrmAddressKeyStore string `json:"-"`
	DcrmAddressPassword string `json:"-"`
	DcrmAddressKeyFile  string `json:"-"`
	// contains filtered or unexported fields
}

TokenConfig struct

func FindTokenConfig added in v0.3.0

func FindTokenConfig(address string, isSrc bool) (configs []*TokenConfig, pairIDs []string)

FindTokenConfig find by (tx to) address

func GetTokenConfig

func GetTokenConfig(pairID string, isSrc bool) *TokenConfig

GetTokenConfig get token config

func GetTokenConfigsByDirection added in v0.3.0

func GetTokenConfigsByDirection(pairID string, isSwapin bool) (fromTokenConfig, toTokenConfig *TokenConfig)

GetTokenConfigsByDirection get token configs by direction

func (*TokenConfig) CalcAndStoreValue

func (c *TokenConfig) CalcAndStoreValue()

CalcAndStoreValue calc and store value (minus duplicate calculation)

func (*TokenConfig) CheckConfig

func (c *TokenConfig) CheckConfig(isSrc bool) error

CheckConfig check token config

func (*TokenConfig) GetDcrmAddressPrivateKey added in v0.3.0

func (c *TokenConfig) GetDcrmAddressPrivateKey() *ecdsa.PrivateKey

GetDcrmAddressPrivateKey get private key

func (*TokenConfig) IsErc20

func (c *TokenConfig) IsErc20() bool

IsErc20 return if token is erc20

func (*TokenConfig) IsProxyErc20 added in v0.3.0

func (c *TokenConfig) IsProxyErc20() bool

IsProxyErc20 return if token is proxy contract of erc20

func (*TokenConfig) LoadDcrmAddressPrivateKey added in v0.3.0

func (c *TokenConfig) LoadDcrmAddressPrivateKey() error

LoadDcrmAddressPrivateKey load private key

func (*TokenConfig) VerifyDcrmPublicKey added in v0.3.0

func (c *TokenConfig) VerifyDcrmPublicKey() error

VerifyDcrmPublicKey verify public key

type TokenPairConfig added in v0.3.0

type TokenPairConfig struct {
	PairID    string
	SrcToken  *TokenConfig
	DestToken *TokenConfig
}

TokenPairConfig pair config

func AddPairConfig added in v0.3.0

func AddPairConfig(configFile string) (pairConfig *TokenPairConfig, err error)

AddPairConfig add pair config dynamically

func GetTokenPairConfig added in v0.3.0

func GetTokenPairConfig(pairID string) *TokenPairConfig

GetTokenPairConfig get token pair config

func (*TokenPairConfig) CheckConfig added in v0.3.0

func (c *TokenPairConfig) CheckConfig() (err error)

CheckConfig check token pair config

type TxStatus

type TxStatus struct {
	Receipt       interface{} `json:"receipt,omitempty"`
	Confirmations uint64      `json:"confirmations"`
	BlockHeight   uint64      `json:"block_height"`
	BlockHash     string      `json:"block_hash"`
	BlockTime     uint64      `json:"block_time"`
}

TxStatus struct

type TxSwapInfo

type TxSwapInfo struct {
	PairID    string   `json:"pairid"`
	Hash      string   `json:"hash"`
	Height    uint64   `json:"height"`
	Timestamp uint64   `json:"timestamp"`
	From      string   `json:"from"`
	TxTo      string   `json:"txto"`
	To        string   `json:"to"`
	Bind      string   `json:"bind"`
	Value     *big.Int `json:"value"`
}

TxSwapInfo struct

Directories

Path Synopsis
btc

Jump to

Keyboard shortcuts

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