-
Notifications
You must be signed in to change notification settings - Fork 1
/
payproto.go
296 lines (275 loc) · 7.52 KB
/
payproto.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
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package payproto
/*
* Dual-licensed under Apache-2.0 and MIT.
*
* You can get a copy of the Apache License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* You can also get a copy of the MIT License at
*
* http://opensource.org/licenses/MIT
*
* @wcgcyx - https://github.com/wcgcyx
*/
import (
"context"
"encoding/json"
"math/big"
"os"
"time"
logging "github.com/ipfs/go-log"
"github.com/libp2p/go-libp2p-core/host"
"github.com/wcgcyx/fcr/crypto"
"github.com/wcgcyx/fcr/locking"
"github.com/wcgcyx/fcr/mdlstore"
"github.com/wcgcyx/fcr/paymgr"
"github.com/wcgcyx/fcr/peermgr"
"github.com/wcgcyx/fcr/peernet/protos/addrproto"
)
const (
DirectPayProtocol = "/fcr-calibr/paynet/pay/direct"
ProxyPayProtocol = "/fcr-calibr/paynet/pay/proxy"
ProtocolVersion = "/0.0.1"
TempKey = "tempkey"
)
// Logger
var log = logging.Logger("payproto")
// PayProtocol manages payment protocol.
// It handles payment.
type PayProtocol struct {
// Host
h host.Host
// Addr proto
addrProto *addrproto.AddrProtocol
// Signer
signer crypto.Signer
// Peer manager
peerMgr peermgr.PeerManager
// Payment manager
payMgr paymgr.PaymentManager
// all recorded received amount.
// Map from currency id -> original addr -> amount received.
// TODO: Maybe give every amount received a timeout, avoid some attacks.
received map[byte]map[string]*big.Int
receivedLock *locking.LockNode
// Process related.
routineCtx context.Context
// Shutdown function.
shutdown func()
// Options
tempDir string
ioTimeout time.Duration
opTimeout time.Duration
cleanFreq time.Duration
cleanTimeout time.Duration
}
// NewPayProtocol creates a new payment protocol.
//
// @input - context, host, addr protocol, signer, peer manager, payment manager, options.
//
// @output - payment protocol, error.
func NewPayProtocol(
ctx context.Context,
h host.Host,
addrProto *addrproto.AddrProtocol,
signer crypto.Signer,
peerMgr peermgr.PeerManager,
payMgr paymgr.PaymentManager,
opts Opts,
) (*PayProtocol, error) {
// Parse options
ioTimeout := opts.IOTimeout
if ioTimeout == 0 {
ioTimeout = defaultIOTimeout
}
opTimeout := opts.OpTimeout
if opTimeout == 0 {
opTimeout = defaultOpTimeout
}
cleanFreq := opts.CleanFreq
if cleanFreq == 0 {
cleanFreq = defaultCleanFreq
}
cleanTimeout := opts.CleanTimeout
if cleanTimeout == 0 {
cleanTimeout = defaultCleanTimeout
}
log.Infof("Start pay protocol...")
// Open the temp ds
ds, err := mdlstore.NewMultiDimLockableStoreImpl(ctx, opts.Path)
if err != nil {
log.Errorf("Fail to open mdlstore: %v", err.Error())
return nil, err
}
defer func() {
err = ds.Shutdown(context.Background())
if err != nil {
log.Errorf("Fail to close temp ds: %v", err.Error())
}
}()
// Load received
var received map[byte]map[string]*big.Int
receivedLock := locking.CreateLockNode()
txn, err := ds.NewTransaction(ctx, true)
if err != nil {
log.Errorf("Fail to start new transaction: %v", err.Error())
return nil, err
}
defer txn.Discard(context.Background())
exists, err := txn.Has(ctx, TempKey)
if err != nil {
log.Errorf("Fail to check if contains %v: %v", TempKey, err.Error())
return nil, err
}
if exists {
dsVal, err := txn.Get(ctx, TempKey)
if err != nil {
log.Errorf("Fail to read ds value for %v: %v", TempKey, err.Error())
return nil, err
}
err = json.Unmarshal(dsVal, &received)
if err != nil {
log.Errorf("Fail to decode ds value: %v", err.Error())
return nil, err
}
for currencyID, addrs := range received {
for addr := range addrs {
receivedLock.Insert(currencyID, addr)
}
}
} else {
received = make(map[byte]map[string]*big.Int)
}
// Create routine
routineCtx, cancel := context.WithCancel(context.Background())
proto := &PayProtocol{
h: h,
addrProto: addrProto,
signer: signer,
peerMgr: peerMgr,
payMgr: payMgr,
received: received,
receivedLock: receivedLock,
routineCtx: routineCtx,
tempDir: opts.Path,
ioTimeout: ioTimeout,
opTimeout: opTimeout,
cleanFreq: cleanFreq,
cleanTimeout: cleanTimeout,
}
h.SetStreamHandler(DirectPayProtocol+ProtocolVersion, proto.handleDirectPay)
h.SetStreamHandler(ProxyPayProtocol+ProtocolVersion, proto.handleProxyPay)
proto.shutdown = func() {
log.Infof("Remove stream handler...")
// Remove stream handler
h.RemoveStreamHandler(DirectPayProtocol + ProtocolVersion)
h.RemoveStreamHandler(ProxyPayProtocol + ProtocolVersion)
// Close routines
log.Infof("Stop all routines...")
cancel()
// Save received
_, err = proto.receivedLock.Lock(context.Background())
if err != nil {
log.Errorf("Fail to obtain lock for received amount: %v", err.Error())
}
// Clear the current temp ds.
err = os.RemoveAll(proto.tempDir)
if err != nil {
log.Errorf("Fail to clear temp ds: %v", err.Error())
}
err = os.Mkdir(proto.tempDir, os.ModePerm)
if err != nil {
log.Errorf("Fail to create temp dir: %v", err.Error())
}
ds, err := mdlstore.NewMultiDimLockableStoreImpl(context.Background(), proto.tempDir)
if err != nil {
log.Errorf("Error creating temp ds to store pay protocol received data: %v", err.Error())
}
var txn mdlstore.Transaction
if ds != nil {
txn, err = ds.NewTransaction(context.Background(), false)
if err != nil {
log.Errorf("Fail to start new transaction: %v", err.Error())
} else {
defer txn.Discard(context.Background())
}
}
defer func() {
if ds != nil {
err = ds.Shutdown(context.Background())
if err != nil {
log.Errorf("Fail to close temp ds: %v", err.Error())
}
}
}()
if txn != nil {
dsVal, err := json.Marshal(received)
if err != nil {
log.Errorf("Fail to encode received amount %v: %v", received, err.Error())
} else {
if err = txn.Put(context.Background(), dsVal, TempKey); err != nil {
log.Errorf("Fail to put %v in %v: %v", dsVal, TempKey, err.Error())
}
}
err = txn.Commit(context.Background())
if err != nil {
log.Errorf("Fail to commit transaction: %v", err.Error())
}
}
}
go proto.cleanRoutine()
return proto, nil
}
// Shutdown safely shuts down the component.
func (p *PayProtocol) Shutdown() {
log.Infof("Start shutdown...")
p.shutdown()
}
// Receive receives amount for given peer.
//
// @input - context, currency id, original address.
//
// @output - amount received, error.
func (p *PayProtocol) Receive(ctx context.Context, currencyID byte, originalAddr string) (*big.Int, error) {
log.Debugf("Receive amount for %v-%v", currencyID, originalAddr)
// Do a check first
release, err := p.receivedLock.RLock(ctx, currencyID, originalAddr)
if err != nil {
log.Debugf("Fail to obtain read lock for %v-%v: %v", currencyID, originalAddr, err.Error())
return nil, err
}
_, ok := p.received[currencyID]
if !ok {
release()
return big.NewInt(0), nil
}
_, ok = p.received[currencyID][originalAddr]
if !ok {
release()
return big.NewInt(0), nil
}
if p.received[currencyID][originalAddr].Cmp(big.NewInt(0)) == 0 {
release()
return big.NewInt(0), nil
}
// Switch from read to write
release()
release, err = p.receivedLock.Lock(ctx, currencyID, originalAddr)
if err != nil {
log.Debugf("Fail to obtain write lock for %v-%v: %v", currencyID, originalAddr, err.Error())
return nil, err
}
defer release()
_, ok = p.received[currencyID]
if !ok {
return big.NewInt(0), nil
}
_, ok = p.received[currencyID][originalAddr]
if !ok {
return big.NewInt(0), nil
}
res := big.NewInt(0).Set(p.received[currencyID][originalAddr])
p.received[currencyID][originalAddr] = big.NewInt(0)
return res, nil
}