-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathosp_webapi_backend.go
More file actions
215 lines (190 loc) · 6.74 KB
/
Copy pathosp_webapi_backend.go
File metadata and controls
215 lines (190 loc) · 6.74 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright 2018-2025 Celer Network
package main
import (
"bytes"
"errors"
"time"
"github.com/celer-network/agent-pay/cnode"
"github.com/celer-network/agent-pay/common"
enums "github.com/celer-network/agent-pay/common/structs"
"github.com/celer-network/agent-pay/config"
"github.com/celer-network/agent-pay/ctype"
"github.com/celer-network/agent-pay/entity"
"github.com/celer-network/agent-pay/utils"
"github.com/celer-network/agent-pay/webapi"
webrpc "github.com/celer-network/agent-pay/webapi/rpc"
"google.golang.org/protobuf/types/known/anypb"
)
// ospWebapiDefaultPayTimeoutSec is the resolve-deadline window used by the
// `SendToken` WebAPI shortcut, which doesn't take a caller-supplied timeout.
// The deadline is `now + this value` (seconds), and must be long enough to
// cover the source→destination forward, the reveal-secret round-trip, and any
// settle-request retry under load. 600s (10 min) gives multi-hop crossnet
// payments comfortable headroom while still being short enough that abandoned
// pays expire promptly.
const ospWebapiDefaultPayTimeoutSec = uint64(600)
var _ webapi.OspPayBackend = (*ospWebapiBackend)(nil)
type ospWebapiBackend struct {
cNode *cnode.CNode
myAddr ctype.Addr
}
func newOspWebapiBackend(cNode *cnode.CNode) *ospWebapiBackend {
return &ospWebapiBackend{
cNode: cNode,
myAddr: cNode.EthAddress,
}
}
func (b *ospWebapiBackend) SendToken(request *webrpc.SendTokenRequest) (ctype.PayIDType, error) {
return b.sendBooleanPayment(request.GetTokenInfo(), request.GetDestination(), request.GetAmount(), nil, ospWebapiDefaultPayTimeoutSec, request.GetNote())
}
func (b *ospWebapiBackend) SendConditionalPayment(request *webrpc.SendConditionalPaymentRequest) (ctype.PayIDType, error) {
if request.GetTransferLogicType() != entity.TransferFunctionType_BOOLEAN_AND {
return ctype.ZeroPayID, errors.New("Unsupported transfer logic type")
}
conditions := make([]*entity.Condition, len(request.GetConditions()))
for i, condition := range request.GetConditions() {
conditions[i] = &entity.Condition{
ConditionType: getConditionType(condition.GetOnChainDeployed()),
DeployedContractAddress: getDeployedContractAddress(condition),
VirtualContractAddress: getVirtualContractAddress(condition),
ArgsQueryFinalization: condition.GetIsFinalizedArgs(),
ArgsQueryOutcome: condition.GetGetOutcomeArgs(),
}
}
return b.sendBooleanPayment(
request.GetTokenInfo(),
request.GetDestination(),
request.GetAmount(),
conditions,
request.GetTimeout(),
request.GetNote())
}
func (b *ospWebapiBackend) CreateAppSessionOnVirtualContract(request *webrpc.CreateAppSessionOnVirtualContractRequest) (string, error) {
return b.cNode.AppClient.NewAppChannelOnVirtualContract(
ctype.Hex2Bytes(request.GetContractBin()),
ctype.Hex2Bytes(request.GetContractConstructor()),
request.GetNonce(),
)
}
func (b *ospWebapiBackend) DeleteAppSession(sessionID string) error {
b.cNode.AppClient.DeleteAppChannel(sessionID)
return nil
}
func (b *ospWebapiBackend) GetIncomingPaymentState(payID ctype.PayIDType) (int, error) {
inState, _, _, err := b.cNode.GetDAL().GetPayStates(payID)
return inState, err
}
func (b *ospWebapiBackend) GetIncomingPaymentRecord(payID ctype.PayIDType) (*webapi.PaymentRecord, error) {
pay, note, _, inState, _, _, _, found, err := b.cNode.GetDAL().GetPaymentInfo(payID)
if err != nil {
return nil, err
}
if !found || pay == nil || inState == enums.PayState_NULL || !bytes.Equal(pay.GetDest(), b.myAddr.Bytes()) {
return nil, common.ErrPayNotFound
}
return &webapi.PaymentRecord{PayID: payID, Pay: pay, Note: note, PayState: inState}, nil
}
func (b *ospWebapiBackend) GetOutgoingPaymentState(payID ctype.PayIDType) (int, error) {
_, outState, _, err := b.cNode.GetDAL().GetPayStates(payID)
return outState, err
}
func (b *ospWebapiBackend) ConfirmOutgoingPayment(payID ctype.PayIDType) error {
return b.cNode.ConfirmBooleanPay(payID)
}
func (b *ospWebapiBackend) RejectIncomingPayment(payID ctype.PayIDType) error {
return b.cNode.RejectBooleanPay(payID)
}
func (b *ospWebapiBackend) sendBooleanPayment(
tokenInfo *webrpc.TokenInfo,
destination string,
amount string,
conditions []*entity.Condition,
timeout uint64,
note *anypb.Any) (ctype.PayIDType, error) {
transfer, err := buildTokenTransfer(tokenInfo, destination, amount)
if err != nil {
return ctype.ZeroPayID, err
}
nowTs := uint64(time.Now().Unix())
resolveDeadline := nowTs + timeout
if resolveDeadline <= nowTs {
return ctype.ZeroPayID, common.ErrDeadlinePassed
}
pay := &entity.ConditionalPay{
Src: b.myAddr.Bytes(),
Dest: transfer.Receiver.Account,
Conditions: conditions,
TransferFunc: &entity.TransferFunction{
LogicType: entity.TransferFunctionType_BOOLEAN_AND,
MaxTransfer: transfer,
},
ResolveDeadline: resolveDeadline,
ResolveTimeout: config.PayResolveTimeout,
ChainId: config.ChainId.Uint64(),
}
var payID ctype.PayIDType
for i := 0; i < 10; i++ {
payID, err = b.cNode.AddBooleanPay(pay, note, 0)
if err != common.ErrPendingSimplex {
break
}
time.Sleep(200 * time.Millisecond)
}
return payID, err
}
func buildTokenTransfer(tokenInfo *webrpc.TokenInfo, destination string, amount string) (*entity.TokenTransfer, error) {
if tokenInfo == nil {
return nil, errors.New("Missing token info")
}
destAddr, err := utils.ValidateAndFormatAddress(destination)
if err != nil {
return nil, err
}
amt := utils.Wei2BigInt(amount)
if amt == nil {
return nil, common.ErrInvalidAmount
}
entityToken, err := webTokenToEntityToken(tokenInfo)
if err != nil {
return nil, err
}
return &entity.TokenTransfer{
Token: entityToken,
Receiver: &entity.AccountAmtPair{
Account: destAddr.Bytes(),
Amt: amt.Bytes(),
},
}, nil
}
func webTokenToEntityToken(tokenInfo *webrpc.TokenInfo) (*entity.TokenInfo, error) {
switch tokenInfo.GetTokenType() {
case entity.TokenType_NATIVE:
return &entity.TokenInfo{TokenType: entity.TokenType_NATIVE}, nil
case entity.TokenType_ERC20:
tokenAddr, err := utils.ValidateAndFormatAddress(tokenInfo.GetTokenAddress())
if err != nil {
return nil, err
}
return &entity.TokenInfo{TokenType: entity.TokenType_ERC20, TokenAddress: tokenAddr.Bytes()}, nil
default:
return nil, errors.New("Unknown token type")
}
}
func getConditionType(onChain bool) entity.ConditionType {
if onChain {
return entity.ConditionType_DEPLOYED_CONTRACT
}
return entity.ConditionType_VIRTUAL_CONTRACT
}
func getDeployedContractAddress(condition *webrpc.Condition) []byte {
if condition.GetOnChainDeployed() {
return ctype.Hex2Bytes(condition.GetContractAddress())
}
return nil
}
func getVirtualContractAddress(condition *webrpc.Condition) []byte {
if !condition.GetOnChainDeployed() {
return ctype.Hex2Bytes(condition.GetContractAddress())
}
return nil
}