forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
989 lines (888 loc) · 29.8 KB
/
handlers.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
package service
import (
"encoding/hex"
"errors"
"fmt"
libp2p "gx/ipfs/QmPGxZ1DP2w45WcogpW1h43BvseXbfke9N91qotpoQcUeS/go-libp2p-crypto"
peer "gx/ipfs/QmWUswjn261LSyVxWAEpMVtPdy8zmKBJJfBpG3Qdpa8ZsE/go-libp2p-peer"
"time"
"github.com/OpenBazaar/openbazaar-go/api/notifications"
"github.com/OpenBazaar/openbazaar-go/core"
"github.com/OpenBazaar/openbazaar-go/net"
"github.com/OpenBazaar/openbazaar-go/pb"
"github.com/OpenBazaar/spvwallet"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
hd "github.com/btcsuite/btcutil/hdkeychain"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
)
func (service *OpenBazaarService) HandlerForMsgType(t pb.Message_MessageType) func(peer.ID, *pb.Message, interface{}) (*pb.Message, error) {
switch t {
case pb.Message_PING:
return service.handlePing
case pb.Message_FOLLOW:
return service.handleFollow
case pb.Message_UNFOLLOW:
return service.handleUnFollow
case pb.Message_OFFLINE_ACK:
return service.handleOfflineAck
case pb.Message_OFFLINE_RELAY:
return service.handleOfflineRelay
case pb.Message_ORDER:
return service.handleOrder
case pb.Message_ORDER_CONFIRMATION:
return service.handleOrderConfirmation
case pb.Message_ORDER_CANCEL:
return service.handleOrderCancel
case pb.Message_ORDER_REJECT:
return service.handleReject
case pb.Message_REFUND:
return service.handleRefund
case pb.Message_ORDER_FULFILLMENT:
return service.handleOrderFulfillment
case pb.Message_ORDER_COMPLETION:
return service.handleOrderCompletion
case pb.Message_DISPUTE_OPEN:
return service.handleDisputeOpen
case pb.Message_DISPUTE_UPDATE:
return service.handleDisputeUpdate
case pb.Message_DISPUTE_CLOSE:
return service.handleDisputeClose
case pb.Message_CHAT:
return service.handleChat
case pb.Message_MODERATOR_ADD:
return service.handleModeratorAdd
case pb.Message_MODERATOR_REMOVE:
return service.handleModeratorRemove
default:
return nil
}
}
func (service *OpenBazaarService) handlePing(peer peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received PING message from %s", peer.Pretty())
return pmes, nil
}
func (service *OpenBazaarService) handleFollow(peer peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received FOLLOW message from %s", peer.Pretty())
err := service.datastore.Followers().Put(peer.Pretty())
if err != nil {
return nil, err
}
n := notifications.FollowNotification{peer.Pretty()}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleUnFollow(peer peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received UNFOLLOW message from %s", peer.Pretty())
err := service.datastore.Followers().Delete(peer.Pretty())
if err != nil {
return nil, err
}
n := notifications.UnfollowNotification{peer.Pretty()}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleOfflineAck(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received OFFLINE_ACK message from %s", p.Pretty())
pid, err := peer.IDB58Decode(string(pmes.Payload.Value))
if err != nil {
return nil, err
}
pointer, err := service.datastore.Pointers().Get(pid)
if err != nil {
return nil, err
}
if pointer.CancelID == nil || pointer.CancelID.Pretty() != p.Pretty() {
return nil, errors.New("Peer is not authorized to delete pointer")
}
err = service.datastore.Pointers().Delete(pid)
if err != nil {
return nil, err
}
return nil, nil
}
func (service *OpenBazaarService) handleOfflineRelay(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received OFFLINE_RELAY message from %s", p.Pretty())
// This acts very similarly to attemptDecrypt&handleMessage in the Offline Message Retreiver
// However it does not send an ACK, or worry about message ordering
// Decrypt and unmarshal plaintext
plaintext, err := net.Decrypt(service.node.IpfsNode.PrivateKey, pmes.Payload.Value)
if err != nil {
return nil, err
}
// Unmarshal plaintext
env := pb.Envelope{}
err = proto.Unmarshal(plaintext, &env)
if err != nil {
return nil, err
}
// Validate the signature
ser, err := proto.Marshal(env.Message)
if err != nil {
return nil, err
}
pubkey, err := libp2p.UnmarshalPublicKey(env.Pubkey)
if err != nil {
return nil, err
}
valid, err := pubkey.Verify(ser, env.Signature)
if err != nil || !valid {
return nil, err
}
id, err := peer.IDFromPublicKey(pubkey)
if err != nil {
return nil, err
}
// Get handler for this message type
handler := service.HandlerForMsgType(env.Message.MessageType)
if handler == nil {
log.Debug("Got back nil handler from HandlerForMsgType")
return nil, nil
}
// Dispatch handler
_, err = handler(id, env.Message, true)
if err != nil {
log.Errorf("Handle message error: %s", err)
return nil, err
}
return nil, nil
}
func (service *OpenBazaarService) handleOrder(peer peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received ORDER message from %s", peer.Pretty())
offline, _ := options.(bool)
errorResponse := func(error string) *pb.Message {
a := &any.Any{Value: []byte(error)}
m := &pb.Message{
MessageType: pb.Message_ERROR,
Payload: a,
}
return m
}
contract := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, contract)
if err != nil {
return errorResponse("Could not unmarshal order"), err
}
err = service.node.ValidateOrder(contract)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), nil
}
if contract.BuyerOrder.Payment.Method == pb.Order_Payment_ADDRESS_REQUEST {
total, err := service.node.CalculateOrderTotal(contract)
if err != nil {
log.Error("Error calculating payment amount")
return errorResponse("Error calculating payment amount"), nil
}
if !service.node.ValidatePaymentAmount(total, contract.BuyerOrder.Payment.Amount) {
log.Error("Calculated a different payment amount")
return errorResponse("Calculated a different payment amount"), nil
}
contract, err = service.node.NewOrderConfirmation(contract, true)
if err != nil {
log.Error(err)
return errorResponse("Error building order confirmation"), nil
}
a, err := ptypes.MarshalAny(contract)
if err != nil {
log.Error(err)
return errorResponse("Error building order confirmation"), nil
}
service.node.Datastore.Sales().Put(contract.VendorOrderConfirmation.OrderID, *contract, pb.OrderState_CONFIRMED, false)
m := pb.Message{
MessageType: pb.Message_ORDER_CONFIRMATION,
Payload: a,
}
return &m, nil
} else if contract.BuyerOrder.Payment.Method == pb.Order_Payment_DIRECT {
err := service.node.ValidateDirectPaymentAddress(contract.BuyerOrder)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
addr, err := btcutil.DecodeAddress(contract.BuyerOrder.Payment.Address, service.node.Wallet.Params())
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
script, err := txscript.PayToAddrScript(addr)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
service.node.Wallet.AddWatchedScript(script)
orderId, err := service.node.CalcOrderId(contract.BuyerOrder)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
service.node.Datastore.Sales().Put(orderId, *contract, pb.OrderState_PENDING, false)
return nil, nil
} else if contract.BuyerOrder.Payment.Method == pb.Order_Payment_MODERATED && !offline {
total, err := service.node.CalculateOrderTotal(contract)
if err != nil {
log.Error("Error calculating payment amount")
return errorResponse("Error calculating payment amount"), nil
}
if !service.node.ValidatePaymentAmount(total, contract.BuyerOrder.Payment.Amount) {
log.Error("Calculated a different payment amount")
return errorResponse("Calculated a different payment amount"), nil
}
err = service.node.ValidateModeratedPaymentAddress(contract.BuyerOrder)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
addr, err := btcutil.DecodeAddress(contract.BuyerOrder.Payment.Address, service.node.Wallet.Params())
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
script, err := txscript.PayToAddrScript(addr)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
service.node.Wallet.AddWatchedScript(script)
contract, err = service.node.NewOrderConfirmation(contract, false)
if err != nil {
log.Error(err)
return errorResponse("Error building order confirmation"), nil
}
a, err := ptypes.MarshalAny(contract)
if err != nil {
log.Error(err)
return errorResponse("Error building order confirmation"), nil
}
service.node.Datastore.Sales().Put(contract.VendorOrderConfirmation.OrderID, *contract, pb.OrderState_CONFIRMED, false)
m := pb.Message{
MessageType: pb.Message_ORDER_CONFIRMATION,
Payload: a,
}
return &m, nil
} else if contract.BuyerOrder.Payment.Method == pb.Order_Payment_MODERATED && offline {
err := service.node.ValidateModeratedPaymentAddress(contract.BuyerOrder)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
addr, err := btcutil.DecodeAddress(contract.BuyerOrder.Payment.Address, service.node.Wallet.Params())
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
script, err := txscript.PayToAddrScript(addr)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
service.node.Wallet.AddWatchedScript(script)
orderId, err := service.node.CalcOrderId(contract.BuyerOrder)
if err != nil {
log.Error(err)
return errorResponse(err.Error()), err
}
service.node.Datastore.Sales().Put(orderId, *contract, pb.OrderState_PENDING, false)
return nil, nil
}
log.Error("Unrecognized payment type")
return errorResponse("Unrecognized payment type"), nil
}
func (service *OpenBazaarService) handleOrderConfirmation(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received ORDER_CONFIRMATION message from %s", p.Pretty())
// Unmarshal payload
vendorContract := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, vendorContract)
if err != nil {
return nil, fmt.Errorf("Could not unmarshal ORDER_CONFIRMATION from %s", p.Pretty())
}
// Calc order ID
orderId := vendorContract.VendorOrderConfirmation.OrderID
// Load the order
contract, _, _, _, _, err := service.datastore.Purchases().GetByOrderId(orderId)
if err != nil {
return nil, err
}
// Validate the order confirmation
err = service.node.ValidateOrderConfirmation(vendorContract, false)
if err != nil {
return nil, err
}
// Append the order confirmation
contract.VendorOrderConfirmation = vendorContract.VendorOrderConfirmation
for _, sig := range vendorContract.Signatures {
if sig.Section == pb.Signature_ORDER_CONFIRMATION {
contract.Signatures = append(contract.Signatures, sig)
}
}
// Set message state to confirmed
service.datastore.Purchases().Put(orderId, *contract, pb.OrderState_CONFIRMED, false)
// Send notification to websocket
n := notifications.OrderConfirmationNotification{orderId}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleOrderCancel(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received ORDER_CANCEL message from %s", p.Pretty())
orderId := string(pmes.Payload.Value)
// Load the order
contract, _, _, _, _, err := service.datastore.Sales().GetByOrderId(orderId)
if err != nil {
return nil, err
}
// Set message state to canceled
service.datastore.Sales().Put(orderId, *contract, pb.OrderState_CANCELED, false)
return nil, nil
}
func (service *OpenBazaarService) handleReject(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received REJECT message from %s", p.Pretty())
rejectMsg := new(pb.OrderReject)
err := ptypes.UnmarshalAny(pmes.Payload, rejectMsg)
if err != nil {
return nil, err
}
// Load the order
contract, _, _, records, _, err := service.datastore.Purchases().GetByOrderId(rejectMsg.OrderID)
if err != nil {
return nil, err
}
if contract.BuyerOrder.Payment.Method != pb.Order_Payment_MODERATED {
// Sweep the address into our wallet
var utxos []spvwallet.Utxo
for _, r := range records {
if !r.Spent && r.Value > 0 {
u := spvwallet.Utxo{}
scriptBytes, err := hex.DecodeString(r.ScriptPubKey)
if err != nil {
return nil, err
}
u.ScriptPubkey = scriptBytes
hash, err := chainhash.NewHashFromStr(r.Txid)
if err != nil {
return nil, err
}
outpoint := wire.NewOutPoint(hash, r.Index)
u.Op = *outpoint
u.Value = r.Value
utxos = append(utxos, u)
}
}
chaincode, err := hex.DecodeString(contract.BuyerOrder.Payment.Chaincode)
if err != nil {
return nil, err
}
parentFP := []byte{0x00, 0x00, 0x00, 0x00}
mPrivKey := service.node.Wallet.MasterPrivateKey()
if err != nil {
return nil, err
}
mECKey, err := mPrivKey.ECPrivKey()
if err != nil {
return nil, err
}
hdKey := hd.NewExtendedKey(
service.node.Wallet.Params().HDPrivateKeyID[:],
mECKey.Serialize(),
chaincode,
parentFP,
0,
0,
true)
buyerKey, err := hdKey.Child(0)
if err != nil {
return nil, err
}
redeemScript, err := hex.DecodeString(contract.BuyerOrder.Payment.RedeemScript)
refundAddress, err := btcutil.DecodeAddress(contract.BuyerOrder.RefundAddress, service.node.Wallet.Params())
if err != nil {
return nil, err
}
_, err = service.node.Wallet.SweepAddress(utxos, &refundAddress, buyerKey, &redeemScript, spvwallet.NORMAL)
if err != nil {
return nil, err
}
} else {
var ins []spvwallet.TransactionInput
var outValue int64
for _, r := range records {
if !r.Spent && r.Value > 0 {
outpointHash, err := hex.DecodeString(r.Txid)
if err != nil {
return nil, err
}
outValue += r.Value
in := spvwallet.TransactionInput{OutpointIndex: r.Index, OutpointHash: outpointHash}
ins = append(ins, in)
}
}
refundAddress, err := btcutil.DecodeAddress(contract.BuyerOrder.RefundAddress, service.node.Wallet.Params())
if err != nil {
return nil, err
}
var output spvwallet.TransactionOutput
outputScript, err := txscript.PayToAddrScript(refundAddress)
if err != nil {
return nil, err
}
output.ScriptPubKey = outputScript
output.Value = outValue
chaincode, err := hex.DecodeString(contract.BuyerOrder.Payment.Chaincode)
if err != nil {
return nil, err
}
parentFP := []byte{0x00, 0x00, 0x00, 0x00}
mPrivKey := service.node.Wallet.MasterPrivateKey()
if err != nil {
return nil, err
}
mECKey, err := mPrivKey.ECPrivKey()
if err != nil {
return nil, err
}
hdKey := hd.NewExtendedKey(
service.node.Wallet.Params().HDPrivateKeyID[:],
mECKey.Serialize(),
chaincode,
parentFP,
0,
0,
true)
buyerKey, err := hdKey.Child(0)
if err != nil {
return nil, err
}
redeemScript, err := hex.DecodeString(contract.BuyerOrder.Payment.RedeemScript)
buyerSignatures, err := service.node.Wallet.CreateMultisigSignature(ins, []spvwallet.TransactionOutput{output}, buyerKey, redeemScript, contract.BuyerOrder.RefundFee)
if err != nil {
return nil, err
}
var vendorSignatures []spvwallet.Signature
for _, s := range rejectMsg.Sigs {
sig := spvwallet.Signature{InputIndex: s.InputIndex, Signature: s.Signature}
vendorSignatures = append(vendorSignatures, sig)
}
err = service.node.Wallet.Multisign(ins, []spvwallet.TransactionOutput{output}, buyerSignatures, vendorSignatures, redeemScript, contract.BuyerOrder.RefundFee)
if err != nil {
return nil, err
}
}
// Set message state to rejected
service.datastore.Purchases().Put(rejectMsg.OrderID, *contract, pb.OrderState_REJECTED, false)
// Send notification to websocket
n := notifications.OrderCancelNotification{rejectMsg.OrderID}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleRefund(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received REFUND message from %s", p.Pretty())
rc := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, rc)
if err != nil {
return nil, err
}
if err := service.node.VerifySignaturesOnRefund(rc); err != nil {
return nil, err
}
// Load the order
contract, _, _, records, _, err := service.datastore.Purchases().GetByOrderId(rc.Refund.OrderID)
if err != nil {
return nil, err
}
if contract.BuyerOrder.Payment.Method == pb.Order_Payment_MODERATED {
var ins []spvwallet.TransactionInput
var outValue int64
for _, r := range records {
if !r.Spent && r.Value > 0 {
outpointHash, err := hex.DecodeString(r.Txid)
if err != nil {
return nil, err
}
outValue += r.Value
in := spvwallet.TransactionInput{OutpointIndex: r.Index, OutpointHash: outpointHash}
ins = append(ins, in)
}
}
refundAddress, err := btcutil.DecodeAddress(contract.BuyerOrder.RefundAddress, service.node.Wallet.Params())
if err != nil {
return nil, err
}
var output spvwallet.TransactionOutput
outputScript, err := txscript.PayToAddrScript(refundAddress)
if err != nil {
return nil, err
}
output.ScriptPubKey = outputScript
output.Value = outValue
chaincode, err := hex.DecodeString(contract.BuyerOrder.Payment.Chaincode)
if err != nil {
return nil, err
}
parentFP := []byte{0x00, 0x00, 0x00, 0x00}
mPrivKey := service.node.Wallet.MasterPrivateKey()
if err != nil {
return nil, err
}
mECKey, err := mPrivKey.ECPrivKey()
if err != nil {
return nil, err
}
hdKey := hd.NewExtendedKey(
service.node.Wallet.Params().HDPrivateKeyID[:],
mECKey.Serialize(),
chaincode,
parentFP,
0,
0,
true)
buyerKey, err := hdKey.Child(0)
if err != nil {
return nil, err
}
redeemScript, err := hex.DecodeString(contract.BuyerOrder.Payment.RedeemScript)
if err != nil {
return nil, err
}
buyerSignatures, err := service.node.Wallet.CreateMultisigSignature(ins, []spvwallet.TransactionOutput{output}, buyerKey, redeemScript, contract.BuyerOrder.RefundFee)
if err != nil {
return nil, err
}
var vendorSignatures []spvwallet.Signature
for _, s := range rc.Refund.Sigs {
sig := spvwallet.Signature{InputIndex: s.InputIndex, Signature: s.Signature}
vendorSignatures = append(vendorSignatures, sig)
}
err = service.node.Wallet.Multisign(ins, []spvwallet.TransactionOutput{output}, buyerSignatures, vendorSignatures, redeemScript, contract.BuyerOrder.RefundFee)
if err != nil {
return nil, err
}
}
contract.Refund = rc.Refund
for _, sig := range contract.Signatures {
if sig.Section == pb.Signature_REFUND {
contract.Signatures = append(contract.Signatures, sig)
}
}
// Set message state to refunded
service.datastore.Purchases().Put(contract.Refund.OrderID, *contract, pb.OrderState_REFUNDED, false)
// Send notification to websocket
n := notifications.RefundNotification{contract.Refund.OrderID}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleOrderFulfillment(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received ORDER_FULFILLMENT message from %s", p.Pretty())
rc := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, rc)
if err != nil {
return nil, err
}
// Load the order
contract, _, _, _, _, err := service.datastore.Purchases().GetByOrderId(rc.VendorOrderFulfillment[0].OrderId)
if err != nil {
return nil, err
}
contract.VendorOrderFulfillment = append(contract.VendorOrderFulfillment, rc.VendorOrderFulfillment[0])
for _, sig := range rc.Signatures {
if sig.Section == pb.Signature_ORDER_FULFILLMENT {
contract.Signatures = append(contract.Signatures, sig)
}
}
if err := service.node.ValidateOrderFulfillment(rc.VendorOrderFulfillment[0], contract); err != nil {
return nil, err
}
// Set message state to fulfilled if all listings have a matching fulfillment message
if service.node.IsFulfilled(contract) {
service.datastore.Purchases().Put(rc.VendorOrderFulfillment[0].OrderId, *contract, pb.OrderState_FULFILLED, false)
}
// Send notification to websocket
n := notifications.FulfillmentNotification{rc.VendorOrderFulfillment[0].OrderId}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleOrderCompletion(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received ORDER_COMPLETION message from %s", p.Pretty())
rc := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, rc)
if err != nil {
return nil, err
}
// Load the order
contract, state, _, records, _, err := service.datastore.Sales().GetByOrderId(rc.BuyerOrderCompletion.OrderId)
if err != nil {
return nil, err
}
contract.BuyerOrderCompletion = rc.BuyerOrderCompletion
for _, sig := range rc.Signatures {
if sig.Section == pb.Signature_ORDER_COMPLETION {
contract.Signatures = append(contract.Signatures, sig)
}
}
if err := service.node.ValidateOrderCompletion(contract); err != nil {
return nil, err
}
if contract.BuyerOrder.Payment.Method == pb.Order_Payment_MODERATED && state != pb.OrderState_RESOLVED {
var ins []spvwallet.TransactionInput
var outValue int64
for _, r := range records {
if !r.Spent && r.Value > 0 {
outpointHash, err := hex.DecodeString(r.Txid)
if err != nil {
return nil, err
}
outValue += r.Value
in := spvwallet.TransactionInput{OutpointIndex: r.Index, OutpointHash: outpointHash}
ins = append(ins, in)
}
}
payoutAddress, err := btcutil.DecodeAddress(contract.VendorOrderFulfillment[0].Payout.PayoutAddress, service.node.Wallet.Params())
if err != nil {
return nil, err
}
var output spvwallet.TransactionOutput
outputScript, err := txscript.PayToAddrScript(payoutAddress)
if err != nil {
return nil, err
}
output.ScriptPubKey = outputScript
output.Value = outValue
redeemScript, err := hex.DecodeString(contract.BuyerOrder.Payment.RedeemScript)
if err != nil {
return nil, err
}
var vendorSignatures []spvwallet.Signature
for _, s := range contract.VendorOrderFulfillment[0].Payout.Sigs {
sig := spvwallet.Signature{InputIndex: s.InputIndex, Signature: s.Signature}
vendorSignatures = append(vendorSignatures, sig)
}
var buyerSignatures []spvwallet.Signature
for _, s := range contract.BuyerOrderCompletion.PayoutSigs {
sig := spvwallet.Signature{InputIndex: s.InputIndex, Signature: s.Signature}
buyerSignatures = append(buyerSignatures, sig)
}
err = service.node.Wallet.Multisign(ins, []spvwallet.TransactionOutput{output}, buyerSignatures, vendorSignatures, redeemScript, contract.VendorOrderFulfillment[0].Payout.PayoutFeePerByte)
if err != nil {
return nil, err
}
}
err = service.node.ValidateAndSaveRating(contract)
if err != nil {
log.Error(err)
}
// Set message state to complete
service.datastore.Sales().Put(rc.BuyerOrderCompletion.OrderId, *contract, pb.OrderState_COMPLETE, false)
// Send notification to websocket
n := notifications.CompletionNotification{rc.BuyerOrderCompletion.OrderId}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleDisputeOpen(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received DISPUTE_OPEN message from %s", p.Pretty())
// Unmarshall
rc := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, rc)
if err != nil {
return nil, err
}
// Verify signature
err = service.node.VerifySignatureOnDisputeOpen(rc, p.Pretty())
if err != nil {
return nil, err
}
// Process message
err = service.node.ProcessDisputeOpen(rc, p.Pretty())
if err != nil {
return nil, err
}
return nil, nil
}
func (service *OpenBazaarService) handleDisputeUpdate(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received DISPUTE_UPDATE message from %s", p.Pretty())
// Make sure we aren't currently processing any disputes before proceeding
core.DisputeWg.Wait()
// Unmarshall
update := new(pb.DisputeUpdate)
err := ptypes.UnmarshalAny(pmes.Payload, update)
if err != nil {
return nil, err
}
buyerContract, vendorContract, _, _, _, _, _, err := service.node.Datastore.Cases().GetPayoutDetails(update.OrderId)
if err != nil {
return nil, err
}
rc := new(pb.RicardianContract)
err = proto.Unmarshal(update.SerializedContract, rc)
if err != nil {
return nil, err
}
if buyerContract == nil {
buyerValidationErrors := service.node.ValidateCaseContract(rc)
err = service.node.Datastore.Cases().UpdateBuyerInfo(update.OrderId, rc, buyerValidationErrors, update.PayoutAddress, update.Outpoints)
if err != nil {
return nil, err
}
} else if vendorContract == nil {
vendorValidationErrors := service.node.ValidateCaseContract(rc)
err = service.node.Datastore.Cases().UpdateVendorInfo(update.OrderId, rc, vendorValidationErrors, update.PayoutAddress, update.Outpoints)
if err != nil {
return nil, err
}
} else {
return nil, errors.New("All contracts have already been received")
}
// Send notification to websocket
n := notifications.DisputeUpdateNotification{update.OrderId}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleDisputeClose(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received DISPUTE_CLOSE message from %s", p.Pretty())
// Unmarshall
rc := new(pb.RicardianContract)
err := ptypes.UnmarshalAny(pmes.Payload, rc)
if err != nil {
return nil, err
}
// Load the order
isPurchase := false
var contract *pb.RicardianContract
contract, _, _, _, _, err = service.datastore.Sales().GetByOrderId(rc.DisputeResolution.OrderId)
if err != nil {
contract, _, _, _, _, err = service.datastore.Purchases().GetByOrderId(rc.DisputeResolution.OrderId)
if err != nil {
return nil, err
}
isPurchase = true
}
// Validate
contract.DisputeResolution = rc.DisputeResolution
for _, sig := range rc.Signatures {
if sig.Section == pb.Signature_DISPUTE_RESOLUTION {
contract.Signatures = append(contract.Signatures, sig)
}
}
err = service.node.ValidateDisputeResolution(contract)
if err != nil {
return nil, err
}
// Save to database
contract.DisputeResolution = rc.DisputeResolution
for _, sig := range rc.Signatures {
if sig.Section == pb.Signature_DISPUTE_RESOLUTION {
contract.Signatures = append(contract.Signatures, sig)
}
}
if isPurchase {
// Set message state to complete
err = service.datastore.Purchases().Put(rc.DisputeResolution.OrderId, *contract, pb.OrderState_DECIDED, false)
} else {
err = service.datastore.Sales().Put(rc.DisputeResolution.OrderId, *contract, pb.OrderState_DECIDED, false)
}
if err != nil {
return nil, err
}
// Send notification to websocket
n := notifications.DisputeCloseNotification{rc.DisputeResolution.OrderId}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleChat(p peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received CHAT message from %s", p.Pretty())
// Unmarshall
chat := new(pb.Chat)
err := ptypes.UnmarshalAny(pmes.Payload, chat)
if err != nil {
return nil, err
}
if chat.Flag == pb.Chat_TYPING {
n := notifications.ChatTyping{
PeerId: p.Pretty(),
Subject: chat.Subject,
}
service.broadcast <- notifications.Serialize(n)
return nil, nil
}
if chat.Flag == pb.Chat_READ {
n := notifications.ChatRead{
PeerId: p.Pretty(),
Subject: chat.Subject,
MessageId: chat.MessageId,
}
service.broadcast <- n
_, _, err = service.datastore.Chat().MarkAsRead(p.Pretty(), chat.Subject, true, chat.MessageId)
if err != nil {
return nil, err
}
return nil, nil
}
// Validate
if len(chat.Subject) > core.CHAT_SUBJECT_MAX_CHARACTERS {
return nil, errors.New("Chat subject over max characters")
}
if len(chat.Message) > core.CHAT_MESSAGE_MAX_CHARACTERS {
return nil, errors.New("Chat message over max characters")
}
// Use correct timestamp
offline, _ := options.(bool)
var t time.Time
if !offline {
t = time.Now()
} else {
if chat.Timestamp == nil {
return nil, errors.New("Invalid timestamp")
}
t, err = ptypes.Timestamp(chat.Timestamp)
if err != nil {
return nil, err
}
}
// Put to database
err = service.datastore.Chat().Put(chat.MessageId, p.Pretty(), chat.Subject, chat.Message, t, false, false)
if err != nil {
return nil, err
}
// Push to websocket
n := notifications.ChatMessage{
MessageId: chat.MessageId,
PeerId: p.Pretty(),
Subject: chat.Subject,
Message: chat.Message,
Timestamp: t,
}
service.broadcast <- n
return nil, nil
}
func (service *OpenBazaarService) handleModeratorAdd(peer peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received MODERATOR_ADD message from %s", peer.Pretty())
err := service.datastore.ModeratedStores().Put(peer.Pretty())
if err != nil {
return nil, err
}
n := notifications.ModeratorAddNotification{peer.Pretty()}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}
func (service *OpenBazaarService) handleModeratorRemove(peer peer.ID, pmes *pb.Message, options interface{}) (*pb.Message, error) {
log.Debugf("Received MODERATOR_REMOVE message from %s", peer.Pretty())
err := service.datastore.ModeratedStores().Delete(peer.Pretty())
if err != nil {
return nil, err
}
n := notifications.ModeratorRemoveNotification{peer.Pretty()}
service.broadcast <- n
service.datastore.Notifications().Put(n, time.Now())
return nil, nil
}