-
Notifications
You must be signed in to change notification settings - Fork 30
/
htlc.go
71 lines (59 loc) · 2.05 KB
/
htlc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package types
import (
"github.com/tendermint/tendermint/crypto/tmhash"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// NewHTLC constructs a new HTLC instance
func NewHTLC(
sender sdk.AccAddress,
to sdk.AccAddress,
receiverOnOtherChain string,
amount sdk.Coins,
secret tmbytes.HexBytes,
timestamp uint64,
expirationHeight uint64,
state HTLCState,
) HTLC {
return HTLC{
Sender: sender.String(),
To: to.String(),
ReceiverOnOtherChain: receiverOnOtherChain,
Amount: amount,
Secret: secret.String(),
Timestamp: timestamp,
ExpirationHeight: expirationHeight,
State: state,
}
}
// Validate validates the HTLC
func (h HTLC) Validate() error {
_, err := sdk.AccAddressFromBech32(h.Sender)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address (%s)", err)
}
if len(h.To) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "recipient missing")
}
if len(h.ReceiverOnOtherChain) > MaxLengthForAddressOnOtherChain {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "length of the receiver on other chain must be between [0,%d]", MaxLengthForAddressOnOtherChain)
}
if !h.Amount.IsValid() || !h.Amount.IsAllPositive() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "the transferred amount must be valid")
}
if h.State != Completed && len(h.Secret) > 0 {
return sdkerrors.Wrapf(ErrInvalidSecret, "secret must be empty when the HTLC has not be claimed")
}
if h.State == Completed && len(h.Secret) != SecretLength {
return sdkerrors.Wrapf(ErrInvalidSecret, "length of the secret must be %d in bytes", SecretLength)
}
return nil
}
// GetHashLock calculates the hash lock from the given secret and timestamp
func GetHashLock(secret tmbytes.HexBytes, timestamp uint64) []byte {
if timestamp > 0 {
return tmhash.Sum(append(secret, sdk.Uint64ToBigEndian(timestamp)...))
}
return tmhash.Sum(secret)
}