encoding

package
v0.0.0-...-9f791b1 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2022 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	//AckCmdID id of Ack message
	AckCmdID = 0
	//PingCmdID id of ping message
	PingCmdID = iota*2 + 1
	//SecretRequestCmdID id of SecretRequest message
	SecretRequestCmdID
	//UnlockCmdID id of Secret message
	UnlockCmdID
	//DirectTransferCmdID id of DirectTransfer, it's now deprecated
	DirectTransferCmdID
	//MediatedTransferCmdID id of MediatedTransfer
	MediatedTransferCmdID
	//AnnounceDisposedTransferCmdID id of AnnounceDisposed message
	AnnounceDisposedTransferCmdID
	//RevealSecretCmdID id of RevealSecret message
	RevealSecretCmdID
	//RemoveExpiredLockCmdID id of RemoveExpiredHashlock message
	RemoveExpiredLockCmdID
	/*
		发起合作关闭通道请求
	*/
	// send CooperativeRequest
	SettleRequestCmdID
	/*
		合作关闭通道响应.
	*/
	SettleResponseCmdID
	/*
		发起提现请求
	*/
	// Send Withdraw Request
	WithdrawRequestCmdID
	/*
		提现响应
	*/
	// Respond Withdraw Request
	WithdrawResponseCmdID
	/*
		refund 响应,
	*/
	// Respond Refund
	AnnounceDisposedTransferResponseCmdID
)

消息设计原则: 只要引起balanceproof 变化,那么 nonce 就应该加1 MessageDesign : as long as balanceproof changes, nonce should plus 1.

Variables

View Source
var IsTest = false

IsTest for test function only

MessageMap contains all message can send and receive. DirectTransfer has been deprecated

View Source
var MessageVersionControlMap = map[int16]int16{
	MediatedTransferCmdID: int16(1),
}

MessageVersionControlMap 保存每个消息支持的最低版本号

Functions

func HashMessageWithoutSignature

func HashMessageWithoutSignature(pack MessagePacker) common.Hash

HashMessageWithoutSignature returns the raw hash of this message

func SignMessage

func SignMessage(privKey *ecdsa.PrivateKey, pack MessagePacker) []byte

SignMessage signs a message

func VerifyMessage

func VerifyMessage(data []byte) (sender common.Address, err error)

VerifyMessage returns the sender of message if data is a valid SignedMessage

Types

type Ack

type Ack struct {
	CmdStruct
	Sender common.Address
	Echo   common.Hash
}

Ack All accepted messages should be confirmed by an `Ack` which echoes the orginals Message hash.

We don'T Sign Acks because attack vector can be mitigated and to speed up things.

func NewAck

func NewAck(sender common.Address, echo common.Hash) *Ack

NewAck create ack message

func (*Ack) Pack

func (ack *Ack) Pack() []byte

Pack implements of MessagePacker

func (*Ack) String

func (ack *Ack) String() string

func (*Ack) UnPack

func (ack *Ack) UnPack(data []byte) error

UnPack is implements of MessageUnpacker

type AnnounceDisposed

type AnnounceDisposed struct {
	SignedMessage
	AnnounceDisposedProof
	ErrorCode int    `json:"error_code"`
	ErrorMsg  string `json:"error_message"`
}

AnnounceDisposed is used for a mediated node who cannot find any next node to send the mediatedTransfer

func NewAnnounceDisposed

func NewAnnounceDisposed(rp *AnnounceDisposedProof, errorCode int, errMsg string) *AnnounceDisposed

NewAnnounceDisposed create AnnounceDisposed

func (*AnnounceDisposed) GetAdditionalHash

func (m *AnnounceDisposed) GetAdditionalHash() common.Hash

GetAdditionalHash return hash of this message

func (*AnnounceDisposed) Pack

func (m *AnnounceDisposed) Pack() []byte

Pack implemnts Messager interface

func (*AnnounceDisposed) Sign

func (m *AnnounceDisposed) Sign(privKey *ecdsa.PrivateKey, msg MessagePacker) error

Sign data=(once+transferamount+locksroot+channel+hash(data))

func (*AnnounceDisposed) String

func (m *AnnounceDisposed) String() string

String is fmt.Stringer

func (*AnnounceDisposed) UnPack

func (m *AnnounceDisposed) UnPack(data []byte) error

UnPack implements MessageUnPacker

type AnnounceDisposedProof

type AnnounceDisposedProof struct {
	Lock *mtree.Lock
	ChannelIDInMessage
}

AnnounceDisposedProof is proof used for contracts

type AnnounceDisposedResponse

type AnnounceDisposedResponse struct {
	EnvelopMessage
	LockSecretHash common.Hash
}

AnnounceDisposedResponse 收到 AnnounceDisposed为对方提供新的权益证明.

func NewAnnounceDisposedResponse

func NewAnnounceDisposedResponse(bp *BalanceProof, lockSecretHash common.Hash) *AnnounceDisposedResponse

NewAnnounceDisposedResponse create

func (*AnnounceDisposedResponse) Pack

func (m *AnnounceDisposedResponse) Pack() []byte

Pack is MessagePacker

func (*AnnounceDisposedResponse) String

func (m *AnnounceDisposedResponse) String() string

String is fmt.Stringer

func (*AnnounceDisposedResponse) UnPack

func (m *AnnounceDisposedResponse) UnPack(data []byte) error

UnPack is MessageUnPacker

type BalanceProof

type BalanceProof struct {
	Nonce             uint64
	ChannelIdentifier common.Hash
	OpenBlockNumber   int64    //open blocknumber 和 channelIdentifier 一起作为通道的唯一标识	// the only tag for a channel = OpenBlockNumber + ChannelIdentifier
	TransferAmount    *big.Int //The number has been transferred to the other party
	Locksroot         common.Hash
}

BalanceProof in the message ,not the same as data need by the contract

func NewBalanceProof

func NewBalanceProof(nonce uint64, transferredAmount *big.Int, locksRoot common.Hash, channelID *contracts.ChannelUniqueID) *BalanceProof

NewBalanceProof create a balance proof

type ChannelIDInMessage

type ChannelIDInMessage struct {
	ChannelIdentifier common.Hash
	OpenBlockNumber   int64
}

ChannelIDInMessage common part of message that don't have a balance proof

type CmdStruct

type CmdStruct struct {
	CmdID       int16
	Version     int16
	InternalTag interface{} //for save to database
}

CmdStruct base of message

func (*CmdStruct) Cmd

func (cmd *CmdStruct) Cmd() int

Cmd id of this message

func (*CmdStruct) Name

func (cmd *CmdStruct) Name() string

Name of this message

func (*CmdStruct) ReadCmdStructFromBuf

func (cmd *CmdStruct) ReadCmdStructFromBuf(buf *bytes.Buffer) (err error)

ReadCmdStructFromBuf read CmdStruct from buf

func (*CmdStruct) SetTag

func (cmd *CmdStruct) SetTag(tag interface{})

SetTag for internal state save

func (*CmdStruct) Tag

func (cmd *CmdStruct) Tag() interface{}

Tag for internal state save

func (*CmdStruct) WriteCmdStructToBuf

func (cmd *CmdStruct) WriteCmdStructToBuf(buf *bytes.Buffer) (err error)

WriteCmdStructToBuf write cmdID and version into buf

type DirectTransfer

type DirectTransfer struct {
	EnvelopMessage
	Data               []byte      // used to transfer custom message, length should < 256
	FakeLockSecretHash common.Hash // used when save transfer status to db, do not be used when message pack/unpack
}

DirectTransfer is a direct token exchange, used when both participants have a previously opened channel.

Signs the unidirectional settled `balance` of `token` to `recipient` plus locked transfers.

Settled refers to the inclusion of formerly locked amounts. Locked amounts are not included in the balance yet, but represented by the `locksroot`.

Args:

nonce: A sequential nonce, used to protected against replay attacks and
    to give a total order for the messages. This nonce is per
    participant, not shared.
token: The address of the token being exchanged in the channel.
transferred_amount: The total amount of token that was transferred to
    the channel partner. This value is monotonically increasing and can
    be larger than a channels deposit, since the channels are
    bidirecional.
recipient: The address of the Photon node participating in the channel.
locksroot: The root of a merkle tree which records the current
    outstanding locks.

func NewDirectTransfer

func NewDirectTransfer(bp *BalanceProof) *DirectTransfer

NewDirectTransfer create DirectTransfer

func (*DirectTransfer) Pack

func (m *DirectTransfer) Pack() []byte

Pack is MessagePacker

func (*DirectTransfer) String

func (m *DirectTransfer) String() string

String is fmt.Stringer

func (*DirectTransfer) UnPack

func (m *DirectTransfer) UnPack(data []byte) error

UnPack is MessageUnPacker

type EnvelopMessage

type EnvelopMessage struct {
	SignedMessage
	BalanceProof
}

EnvelopMessage is general part of message that contains a new balanceproof

func (*EnvelopMessage) GetEnvelopMessage

func (m *EnvelopMessage) GetEnvelopMessage() *EnvelopMessage

GetEnvelopMessage return EnvelopMessage

func (*EnvelopMessage) Sign

func (m *EnvelopMessage) Sign(privKey *ecdsa.PrivateKey, msg MessagePacker) error

Sign data=(once+transferamount+locksroot+channel+hash(data))

func (*EnvelopMessage) String

func (m *EnvelopMessage) String() string

String is fmt.Stringer

type EnvelopMessager

type EnvelopMessager interface {
	SignedMessager
	//GetEnvelopMessage returns EnvelopMessage
	GetEnvelopMessage() *EnvelopMessage
}

EnvelopMessager is message contains new balance proof

type MediatedTransfer

type MediatedTransfer struct {
	EnvelopMessage
	Expiration     int64
	LockSecretHash common.Hash
	PaymentAmount  *big.Int //The number transferred to party
	Target         common.Address
	Initiator      common.Address
	Fee            *big.Int
	Path           []common.Address // 2019-03 消息升级后,带全路径信息
}

MediatedTransfer has a `target` address to which a chain of transfers shall be established. Here the `haslock` is mandatory.

`fee` is the remaining fee a recipient shall use to complete the mediated transfer. The recipient can deduct his own fee from the amount and lower `fee` to the remaining fee. Just as the recipient can fail to forward at all, or the assumed amount, it can deduct a too high fee, but this would render completion of the transfer unlikely.

The initiator of a mediated transfer will calculate fees based on the likely fees along the path. Note, it can not determine the path, as it does not know which nodes are available.

Initial `amount` should be expected received amount + fees.

Fees are always payable by the initiator.

`initiator` is the party that knows the secret to the `hashlock`

func GetMtrFromLockedTransfer

func GetMtrFromLockedTransfer(tr Messager) (mtr *MediatedTransfer)

GetMtrFromLockedTransfer returns the MediatedTransfer ,the caller must maker sure this message is a locked transfer

func NewMediatedTransfer

func NewMediatedTransfer(bp *BalanceProof, lock *mtree.Lock,
	target, initiator common.Address, fee *big.Int, path []common.Address) *MediatedTransfer

NewMediatedTransfer create MediatedTransfer

func (*MediatedTransfer) GetLock

func (m *MediatedTransfer) GetLock() *mtree.Lock

GetLock returns Lock of this Transfer

func (*MediatedTransfer) GetPathStr

func (m *MediatedTransfer) GetPathStr() string

GetPathStr get string of path to print

func (*MediatedTransfer) Pack

func (m *MediatedTransfer) Pack() []byte

Pack is MessagePacker

func (*MediatedTransfer) String

func (m *MediatedTransfer) String() string

String is fmt.Stringer

func (*MediatedTransfer) UnPack

func (m *MediatedTransfer) UnPack(data []byte) error

UnPack is MessageUnPacker

type MessagePacker

type MessagePacker interface {
	//pack message to byte array
	Pack() []byte
}

MessagePacker serialize of a message

type MessagePackerUnpacker

type MessagePackerUnpacker interface {
	MessagePacker
	MessageUnpacker
}

MessagePackerUnpacker is packer and unpacker

type MessageType

type MessageType int

MessageType is the type of message for receive and send

func (MessageType) String

func (t MessageType) String() string

String return the string representation of message type.

type MessageUnpacker

type MessageUnpacker interface {
	//unpack message from byte array
	UnPack(data []byte) error
}

MessageUnpacker deserialize of message

type Messager

type Messager interface {
	//Cmd id of message
	Cmd() int
	//Tag is used for save and restore
	Tag() interface{}
	//SetTag set tage
	SetTag(tag interface{})
	//Name of this message
	Name() string
	//String fmt.Stringer
	String() string
	MessagePackerUnpacker
}

Messager interface for all message type

type Ping

type Ping struct {
	SignedMessage
	Nonce int64
}

Ping message

func NewPing

func NewPing(nonce int64) *Ping

NewPing create ping message

func (*Ping) Pack

func (p *Ping) Pack() []byte

Pack is MessagePacker

func (*Ping) String

func (p *Ping) String() string

String is fmt.Stringer

func (*Ping) UnPack

func (p *Ping) UnPack(data []byte) error

UnPack is MessageUnPacker

type RemoveExpiredHashlockTransfer

type RemoveExpiredHashlockTransfer struct {
	EnvelopMessage
	LockSecretHash common.Hash
}

RemoveExpiredHashlockTransfer message from sender to receiver, notify to remove a expired hashlock, provide new blance proof.

Removes one lock that has expired. Used to trim the merkle tree and recover the locked capacity. This message is only valid if the corresponding lock expiration is lower than the latest block number for the corresponding blockchain. Fields Field Name Field Type Description secrethash bytes32 The secrethash to remove balance_proof BalanceProof The updated balance proof signature bytes Elliptic Curve 256k1 signature

func NewRemoveExpiredHashlockTransfer

func NewRemoveExpiredHashlockTransfer(bp *BalanceProof, lockSecretHash common.Hash) *RemoveExpiredHashlockTransfer

NewRemoveExpiredHashlockTransfer create RemoveExpiredHashlockTransfer

func (*RemoveExpiredHashlockTransfer) Pack

func (m *RemoveExpiredHashlockTransfer) Pack() []byte

Pack is MessagePacker

func (*RemoveExpiredHashlockTransfer) String

String is fmt.Stringer

func (*RemoveExpiredHashlockTransfer) UnPack

func (m *RemoveExpiredHashlockTransfer) UnPack(data []byte) error

UnPack is MessageUnPacker

type RevealSecret

type RevealSecret struct {
	SignedMessage
	LockSecret common.Hash

	Data []byte // used to transfer custom message, length should < 256
	// contains filtered or unexported fields
}

RevealSecret used to reveal a secret to party known to have interest in it.

This message is not sufficient for state changes in the Photon Channel, the reason is that a node participating in split transfer or in both mediated transfer for an exchange might can reveal the secret to it's partners, but that must not update the internal channel state.

func CloneRevealSecret

func CloneRevealSecret(rs *RevealSecret) *RevealSecret

CloneRevealSecret clones a RevealSecret Message

func NewRevealSecret

func NewRevealSecret(lockSecret common.Hash) *RevealSecret

NewRevealSecret create RevealSecret

func (*RevealSecret) LockSecretHash

func (rs *RevealSecret) LockSecretHash() common.Hash

LockSecretHash return hash of secret

func (*RevealSecret) Pack

func (rs *RevealSecret) Pack() []byte

Pack is MessagePacker

func (*RevealSecret) String

func (rs *RevealSecret) String() string

String fmt.Stringer

func (*RevealSecret) UnPack

func (rs *RevealSecret) UnPack(data []byte) error

UnPack is MessageUnPacker

type SecretRequest

type SecretRequest struct {
	SignedMessage
	LockSecretHash common.Hash
	PaymentAmount  *big.Int
}

SecretRequest Requests the secret which unlocks a hashlock.

func NewSecretRequest

func NewSecretRequest(lockSecretHash common.Hash, paymentAmount *big.Int) *SecretRequest

NewSecretRequest create SecretRequest

func (*SecretRequest) Pack

func (sr *SecretRequest) Pack() []byte

Pack is MessagePacker

func (*SecretRequest) String

func (sr *SecretRequest) String() string

String is fmt.Stringer

func (*SecretRequest) UnPack

func (sr *SecretRequest) UnPack(data []byte) error

UnPack is MessageUnpacker

type SettleDataInMessage

type SettleDataInMessage struct {
	ChannelIDInMessage
	Participant1        common.Address
	Participant1Balance *big.Int
	Participant2        common.Address
	Participant2Balance *big.Int
}

SettleDataInMessage common part of settle request and response

type SettleRequest

type SettleRequest struct {
	SignedMessage
	SettleRequestData
}

SettleRequest 向对方提出我要合作关闭通道.

func NewSettleRequest

func NewSettleRequest(wd *SettleRequestData) *SettleRequest

NewSettleRequest create settle request from `SettleRequestData`

func (*SettleRequest) Pack

func (m *SettleRequest) Pack() []byte

Pack is MessagePacker

func (*SettleRequest) Sign

func (m *SettleRequest) Sign(key *ecdsa.PrivateKey, msg MessagePacker) (err error)

Sign is SignedMessager

func (*SettleRequest) SignDataForContract

func (m *SettleRequest) SignDataForContract() []byte

SignDataForContract 生成合约调用签名数据

func (*SettleRequest) String

func (m *SettleRequest) String() string

func (*SettleRequest) UnPack

func (m *SettleRequest) UnPack(data []byte) error

UnPack is MessageUnPacker

type SettleRequestData

type SettleRequestData struct {
	SettleDataInMessage
	Participant1Signature []byte
}

SettleRequestData for contract

type SettleResponse

type SettleResponse struct {
	SignedMessage
	SettleResponseData
	ErrorCode int    `json:"error_code"`
	ErrorMsg  string `json:"error_message"`
}

SettleResponse 相应对方合作关闭通道要求

func NewErrorCooperativeSettleResponseAndSign

func NewErrorCooperativeSettleResponseAndSign(req *SettleRequest, privateKey *ecdsa.PrivateKey, errorCode int, errorMsg string) (res *SettleResponse)

NewErrorCooperativeSettleResponseAndSign 创建返回错误信息的SettleResponse

func NewSettleResponse

func NewSettleResponse(wd *SettleResponseData, errorCode int, errorMsg string) *SettleResponse

NewSettleResponse create settle response from `SettleResponseData`

func (*SettleResponse) Pack

func (m *SettleResponse) Pack() []byte

Pack is MessagePacker

func (*SettleResponse) Sign

func (m *SettleResponse) Sign(key *ecdsa.PrivateKey, msg MessagePacker) (err error)

Sign is SignedMessager

func (*SettleResponse) SignDataForContract

func (m *SettleResponse) SignDataForContract() []byte

SignDataForContract 生成合约调用数据

func (*SettleResponse) String

func (m *SettleResponse) String() string

func (*SettleResponse) UnPack

func (m *SettleResponse) UnPack(data []byte) error

UnPack is MessageUnPacker

type SettleResponseData

type SettleResponseData struct {
	SettleDataInMessage
	Participant2Signature []byte
}

SettleResponseData for contract

type SignedMessage

type SignedMessage struct {
	CmdStruct
	Sender    common.Address
	Signature []byte
}

SignedMessage is corresponding of SignedMessager

func (*SignedMessage) GetSender

func (m *SignedMessage) GetSender() common.Address

GetSender returns the sender of this message

func (*SignedMessage) Sign

func (m *SignedMessage) Sign(priveKey *ecdsa.PrivateKey, pack MessagePacker) error

Sign this message

type SignedMessager

type SignedMessager interface {
	Messager
	GetSender() common.Address
	Sign(priveKey *ecdsa.PrivateKey, pack MessagePacker) error
	// contains filtered or unexported methods
}

SignedMessager interface of message that needs signed

type TestChannelBlockNumberGetter

type TestChannelBlockNumberGetter struct {
}

TestChannelBlockNumberGetter only valid in test,if was used in production environment, always error

func (TestChannelBlockNumberGetter) GetChannelOpenBlockNumber

func (c TestChannelBlockNumberGetter) GetChannelOpenBlockNumber(chID *contracts.ChannelUniqueID) int64

GetChannelOpenBlockNumber only works in

type UnLock

type UnLock struct {
	EnvelopMessage
	LockSecret common.Hash
}

UnLock Message used to do state changes on a partner Photon Channel.

Locksroot changes need to be synchronized among both participants, the protocol is for only the side unlocking to send the Secret message allowing the other party to withdraw.

func NewUnlock

func NewUnlock(bp *BalanceProof, lockSecret common.Hash) *UnLock

NewUnlock create Secret message

func (*UnLock) LockSecretHash

func (s *UnLock) LockSecretHash() common.Hash

LockSecretHash is Hash of secret

func (*UnLock) Pack

func (s *UnLock) Pack() []byte

Pack is MessagePacker

func (*UnLock) String

func (s *UnLock) String() string

String is fmt.Stringer

func (*UnLock) UnPack

func (s *UnLock) UnPack(data []byte) error

UnPack is MessageUnPacker

type WithdrawReponseData

type WithdrawReponseData struct {
	ChannelIDInMessage
	Participant1          common.Address
	Participant2          common.Address
	Participant1Balance   *big.Int
	Participant1Withdraw  *big.Int
	Participant1Signature []byte
	Participant2Signature []byte
}

WithdrawReponseData data for withdrawResponse

type WithdrawRequest

type WithdrawRequest struct {
	SignedMessage
	WithdrawRequestData
}

WithdrawRequest 向对方提出我要不关闭通道取现,节点应该标注通道不可用,然后再发送消息

func NewWithdrawRequest

func NewWithdrawRequest(wd *WithdrawRequestData) *WithdrawRequest

NewWithdrawRequest create withdraw request from `WithdrawRequestData`

func (*WithdrawRequest) Pack

func (m *WithdrawRequest) Pack() []byte

Pack is MessagePacker

func (*WithdrawRequest) Sign

func (m *WithdrawRequest) Sign(key *ecdsa.PrivateKey, msg MessagePacker) (err error)

Sign is SignedMessager

func (*WithdrawRequest) String

func (m *WithdrawRequest) String() string

func (*WithdrawRequest) UnPack

func (m *WithdrawRequest) UnPack(data []byte) error

UnPack is MessageUnPacker

type WithdrawRequestData

type WithdrawRequestData struct {
	ChannelIDInMessage
	Participant1          common.Address
	Participant2          common.Address
	Participant1Balance   *big.Int
	Participant1Withdraw  *big.Int
	Participant1Signature []byte
}

WithdrawRequestData for contract

type WithdrawResponse

type WithdrawResponse struct {
	SignedMessage
	WithdrawReponseData
	ErrorCode int    `json:"error_code"`
	ErrorMsg  string `json:"error_message"`
}

WithdrawResponse is response for partner's withdraw request

func NewErrorWithdrawResponseAndSign

func NewErrorWithdrawResponseAndSign(req *WithdrawRequest, privateKey *ecdsa.PrivateKey, errorCode int, errorMsg string) (res *WithdrawResponse)

NewErrorWithdrawResponseAndSign 创建返回错误信息的SettleResponse

func NewWithdrawResponse

func NewWithdrawResponse(wd *WithdrawReponseData, errorCode int, errorMsg string) *WithdrawResponse

NewWithdrawResponse create withdraw response from `WithdrawReponseData`

func (*WithdrawResponse) Pack

func (m *WithdrawResponse) Pack() []byte

Pack is MessagePacker

func (*WithdrawResponse) Sign

func (m *WithdrawResponse) Sign(key *ecdsa.PrivateKey, msg MessagePacker) (err error)

Sign is SignedMessager

func (*WithdrawResponse) String

func (m *WithdrawResponse) String() string

func (*WithdrawResponse) UnPack

func (m *WithdrawResponse) UnPack(data []byte) error

UnPack is MessageUnPacker

Jump to

Keyboard shortcuts

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