-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtransfer_contract_manager.go
More file actions
1582 lines (1371 loc) · 47.7 KB
/
Copy pathtransfer_contract_manager.go
File metadata and controls
1582 lines (1371 loc) · 47.7 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
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
990
991
992
993
994
995
996
997
998
999
1000
package connect
import (
"context"
"sync"
"sync/atomic"
"time"
// "errors"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"fmt"
// "slices"
// "runtime/debug"
mathrand "math/rand"
"golang.org/x/exp/maps"
// "google.golang.org/protobuf/proto"
"github.com/urnetwork/connect/protocol"
)
var lastOobErrLogNano atomic.Int64
var suppressedOobErrCount atomic.Int64
func shouldLogOobErr() (bool, int64) {
now := time.Now().UnixNano()
last := lastOobErrLogNano.Load()
if now-last < int64(time.Minute) {
suppressedOobErrCount.Add(1)
return false, 0
}
if !lastOobErrLogNano.CompareAndSwap(last, now) {
suppressedOobErrCount.Add(1)
return false, 0
}
suppressed := suppressedOobErrCount.Swap(0)
return true, suppressed
}
// manage contracts which are embedded into each transfer sequence
type ContractKey struct {
Destination TransferPath
IntermediaryIds MultiHopId
CompanionContract bool
ForceStream bool
// EncryptionRole separates the contract queues of the two per-peer
// encryption send sequences to the same destination: the client-role
// sequence (normal application data) and the server-role sequence
// (EncryptedControl carrier + server replies). Without this, both would
// share one queue, and one sequence's exit-flush (`FlushContractQueue`
// on idle) would discard the other's pending contracts — starving the
// handshake carrier. Zero value is client, so non-encrypted traffic and
// legacy/pushed contracts key the same as before.
EncryptionRole sequenceTlsRole
// EncryptionCompanion separates the contract queues of two same-role send
// sequences differing only by session identity companion — the two
// server-role reply carriers that echo a companion vs non-companion
// initiator both ride the same EncryptionControlUseCompanion contract, so
// `CompanionContract` alone doesn't separate them. Without this they share a
// queue and starve each other on exit-flush, as `EncryptionRole` guards for
// the client/server split. Zero value false, so non-encrypted and
// legacy/pushed contracts key as before.
EncryptionCompanion bool
}
func (self ContractKey) Legacy() ContractKey {
return ContractKey{
Destination: self.Destination,
}
}
type ContractStatus struct {
Key ContractKey
Error *protocol.ContractError
Premium bool
}
type ContractStatusFunction = func(ContractStatus *ContractStatus)
type contractStatusCallbackWorker struct {
ctx context.Context
cancel context.CancelFunc
callback ContractStatusFunction
receiveContractStatuses chan *ContractStatus
}
func newContractStatusCallbackWorker(ctx context.Context, callback ContractStatusFunction, bufferSize int) *contractStatusCallbackWorker {
callbackCtx, cancel := context.WithCancel(ctx)
worker := &contractStatusCallbackWorker{
ctx: callbackCtx,
cancel: cancel,
callback: callback,
receiveContractStatuses: make(chan *ContractStatus, bufferSize),
}
go HandleError(worker.run, cancel)
return worker
}
func (self *contractStatusCallbackWorker) run() {
for {
select {
case <-self.ctx.Done():
return
case contractStatus := <-self.receiveContractStatuses:
if self.ctx.Err() != nil {
return
}
HandleError(func() {
self.callback(contractStatus)
})
}
}
}
func (self *contractStatusCallbackWorker) Dispatch(contractStatus *ContractStatus) {
select {
case <-self.ctx.Done():
case self.receiveContractStatuses <- contractStatus:
}
}
func (self *contractStatusCallbackWorker) Close() {
self.cancel()
}
type ContractManagerStats struct {
ContractOpenCount int64
ContractCloseCount int64
// contract id -> byte count
ContractOpenByteCounts map[Id]ByteCount
// contract id -> contract key
ContractOpenKeys map[Id]ContractKey
ContractCloseByteCount ByteCount
ReceiveContractCloseByteCount ByteCount
}
func NewContractManagerStats() *ContractManagerStats {
return &ContractManagerStats{
ContractOpenCount: 0,
ContractCloseCount: 0,
ContractOpenByteCounts: map[Id]ByteCount{},
ContractOpenKeys: map[Id]ContractKey{},
ContractCloseByteCount: 0,
ReceiveContractCloseByteCount: 0,
}
}
func (self *ContractManagerStats) ContractOpenByteCount() ByteCount {
netContractOpenByteCount := ByteCount(0)
for _, contractOpenByteCount := range self.ContractOpenByteCounts {
netContractOpenByteCount += contractOpenByteCount
}
return netContractOpenByteCount
}
// SignStoredContract returns the HMAC signature for a stored contract using the
// format appropriate for the current time relative to
// settings.NetworkEventTimeChangeHmac. Before that time, signers emit the
// legacy form (`mac.Sum(storedContractBytes)`, which appends a key-only HMAC
// to the contract bytes). At or after that time, signers emit the standard
// form (`mac.Write(storedContractBytes); mac.Sum(nil)`).
//
// Both connect and server/connect must use this helper so the cutover is
// consistent across client and server.
func SignStoredContract(settings *ContractManagerSettings, provideSecretKey []byte, storedContractBytes []byte) []byte {
mac := hmac.New(sha256.New, provideSecretKey)
if time.Now().Before(settings.NetworkEventTimeChangeHmac) {
// legacy: this leaves HMAC(key, "") in the trailing 32 bytes of the
// returned slice. preserved for backward compatibility.
return mac.Sum(storedContractBytes)
}
mac.Write(storedContractBytes)
return mac.Sum(nil)
}
// VerifyStoredContract validates a stored-contract HMAC against the provide
// secret key, accepting both the legacy and standard HMAC formats so that
// signers may cross over at settings.NetworkEventTimeChangeHmac without
// breaking compatibility with peers that have not yet cut over.
func VerifyStoredContract(settings *ContractManagerSettings, provideSecretKey []byte, storedContractBytes []byte, storedContractHmac []byte) bool {
legacyMac := hmac.New(sha256.New, provideSecretKey)
if hmac.Equal(storedContractHmac, legacyMac.Sum(storedContractBytes)) {
return true
}
standardMac := hmac.New(sha256.New, provideSecretKey)
standardMac.Write(storedContractBytes)
return hmac.Equal(storedContractHmac, standardMac.Sum(nil))
}
func DefaultContractManagerSettings() *ContractManagerSettings {
return DefaultContractManagerSettingsWithBufferSize(defaultTransferBufferSize)
}
func DefaultContractManagerSettingsWithBufferSize(bufferSize int) *ContractManagerSettings {
// NETWORK EVENT: at the enable contracts date, all clients will require contracts
// up to that time, contracts are optional for the sender and match for the receiver
networkEventTimeEnableContracts, err := time.Parse(time.RFC3339, "2024-05-01T00:00:00Z")
if err != nil {
panic(err)
}
// NETWORK EVENT: at the change-hmac date, signers cut over from the legacy
// HMAC format to the standard form. verifiers accept both forms at all
// times so the cutover can be deployed asymmetrically.
networkEventTimeChangeHmac, err := time.Parse(time.RFC3339, "2026-07-01T00:00:00Z")
if err != nil {
panic(err)
}
return &ContractManagerSettings{
SequenceBufferSize: bufferSize,
InitialContractTransferByteCount: kib(16),
StandardContractTransferByteCount: mib(128),
ContractTransferByteSeqScale: 4,
NetworkEventTimeEnableContracts: networkEventTimeEnableContracts,
NetworkEventTimeChangeHmac: networkEventTimeChangeHmac,
ProvidePingTimeout: 0,
OriginContractLinger: 300 * time.Second,
ContractQueueExpireTimeout: 120 * time.Second,
CreateContractOobErrorBackoff: time.Minute,
ProtocolVersion: DefaultProtocolVersion,
// TODO remove
LegacyCreateContract: false,
// TODO remove
TrackUsedContracts: false,
}
}
func DefaultContractManagerSettingsNoNetworkEvents() *ContractManagerSettings {
settings := DefaultContractManagerSettings()
settings.NetworkEventTimeEnableContracts = time.Time{}
settings.NetworkEventTimeChangeHmac = time.Time{}
return settings
}
type ContractManagerSettings struct {
SequenceBufferSize int
// this should be enough to do a single ping
InitialContractTransferByteCount ByteCount
StandardContractTransferByteCount ByteCount
// scale up the contract size over this many contracts
ContractTransferByteSeqScale uint64
// enable contracts on the network
// this can be removed after wide adoption
NetworkEventTimeEnableContracts time.Time
// cut over the stored-contract HMAC signing format. before this time,
// SignStoredContract emits the legacy form (mac.Sum(bytes)); at or after,
// it emits the standard form (mac.Write(bytes); mac.Sum(nil)). verifiers
// accept both forms at all times.
NetworkEventTimeChangeHmac time.Time
// an active ping to the control fast-tracks any timeouts
ProvidePingTimeout time.Duration
// server-side companion policy: allow a return (companion) contract to be
// created for up to this long after the origin contract in the opposite
// direction was closed, so reply traffic can resume after the request side
// goes idle.
OriginContractLinger time.Duration
// expire queued contracts that no sequence has taken within this window.
// Bounds `destinationContracts` growth from orphans (e.g. a
// `CreateContractResult` that lands after the owning sequence exit-flushed
// its queue, for a destination that is never used again), and prevents
// handing out a stale contract the platform may have already force-closed
// server-side — keep this below the platform's unused-contract force-close
// window (5 minutes). <= 0 disables expiry.
ContractQueueExpireTimeout time.Duration
// back off create-contract OOB API calls after an OOB error to avoid
// repeatedly hitting the API while it is timing out or unavailable.
CreateContractOobErrorBackoff time.Duration
ProtocolVersion int
// TODO remove
LegacyCreateContract bool
// TODO remove
TrackUsedContracts bool
}
func (self *ContractManagerSettings) ContractsEnabled() bool {
return self.NetworkEventTimeEnableContracts.Before(time.Now())
}
type ContractManager struct {
ctx context.Context
client *Client
settings *ContractManagerSettings
mutex sync.Mutex
// `provideSecretKeys` retains all keys until app restart (typically system restart)
// this makes it faster for clients to reconnect with existing contracts
// otherwise the client will have to time out the send sequence and flush its pending contracts
provideSecretKeys map[protocol.ProvideMode][]byte
provideModes map[protocol.ProvideMode]bool
// provide paused overrides the set provide modes
providePaused bool
provideMonitor *Monitor
destinationContracts map[ContractKey]*contractQueue
receiveNoContractClientIds map[Id]bool
sendNoContractClientIds map[Id]bool
contractStatusCallbacks *CallbackList[*contractStatusCallbackWorker]
localStats *ContractManagerStats
controlSyncProvide *ControlSync
controlSyncProvideOob *ControlSyncOob
createContractOobErrorBackoffUntil time.Time
}
func NewContractManagerWithDefaults(ctx context.Context, client *Client) *ContractManager {
return NewContractManager(ctx, client, DefaultContractManagerSettings())
}
func (self *ContractManager) createContractOobErrorBackoffActive() bool {
if self.settings.CreateContractOobErrorBackoff <= 0 {
return false
}
self.mutex.Lock()
defer self.mutex.Unlock()
return time.Now().Before(self.createContractOobErrorBackoffUntil)
}
func (self *ContractManager) markCreateContractOobError() {
if self.settings.CreateContractOobErrorBackoff <= 0 {
return
}
self.mutex.Lock()
defer self.mutex.Unlock()
if !time.Now().Before(self.createContractOobErrorBackoffUntil) {
self.createContractOobErrorBackoffUntil = time.Now().Add(self.settings.CreateContractOobErrorBackoff)
}
}
func NewContractManager(
ctx context.Context,
client *Client,
settings *ContractManagerSettings,
) *ContractManager {
// at a minimum
// - messages to/from the platform (ControlId) do not need a contract
// this is because the platform is needed to create contracts
// - messages to self do not need a contract
receiveNoContractClientIds := map[Id]bool{
ControlId: true,
client.ClientId(): true,
}
sendNoContractClientIds := map[Id]bool{
ControlId: true,
client.ClientId(): true,
}
contractManager := &ContractManager{
ctx: ctx,
client: client,
settings: settings,
provideSecretKeys: map[protocol.ProvideMode][]byte{},
provideModes: map[protocol.ProvideMode]bool{},
providePaused: false,
provideMonitor: NewMonitor(),
destinationContracts: map[ContractKey]*contractQueue{},
receiveNoContractClientIds: receiveNoContractClientIds,
sendNoContractClientIds: sendNoContractClientIds,
contractStatusCallbacks: NewCallbackList[*contractStatusCallbackWorker](),
localStats: NewContractManagerStats(),
controlSyncProvide: NewControlSync(ctx, client, "provide"),
controlSyncProvideOob: NewControlSyncOob(ctx, client, "provide-oob"),
}
if client.ClientId() != ControlId {
go HandleError(contractManager.providePing, client.Cancel)
}
go HandleError(contractManager.expireQueuedContracts, client.Cancel)
return contractManager
}
// expireQueuedContracts periodically closes queued contracts that no sequence
// took within `ContractQueueExpireTimeout` and removes the emptied queues.
// This bounds `destinationContracts` against orphans — e.g. a
// `CreateContractResult` that lands after the owning sequence exit-flushed its
// queue (`FlushContractQueue` force-remove) re-creates the queue entry, and if
// that destination is never used again (provider rotation) the entry would
// otherwise be retained forever.
func (self *ContractManager) expireQueuedContracts() {
timeout := self.settings.ContractQueueExpireTimeout
// the contract manager is closing: close all still-queued (pending)
// contracts so their escrow is released promptly. `closeContracts`
// routes shutdown closes over the out-of-band api on a Background
// context, since the client context (and the in-band transport) is
// already closed.
finalFlush := func() {
pending := []*protocol.Contract{}
func() {
self.mutex.Lock()
defer self.mutex.Unlock()
for contractKey, contractQueue := range self.destinationContracts {
pending = append(pending, contractQueue.Flush(false)...)
if contractQueue.IsDone() {
delete(self.destinationContracts, contractKey)
}
}
}()
if 0 < len(pending) {
self.client.log.V(1).Infof("[contract]closing %d pending contracts on close\n", len(pending))
self.closeContracts(pending)
}
}
for {
// when expiry is disabled the nil tick channel blocks forever and the
// loop only waits for shutdown
var tick <-chan time.Time
if 0 < timeout {
tick = time.After(timeout / 2)
}
select {
case <-self.ctx.Done():
finalFlush()
return
case <-self.client.Done():
// the manager ctx is the client's parent ctx; the client closing
// is the shutdown signal
finalFlush()
return
case <-tick:
}
minEnqueueTime := time.Now().Add(-timeout)
expired := []*protocol.Contract{}
func() {
self.mutex.Lock()
defer self.mutex.Unlock()
for contractKey, contractQueue := range self.destinationContracts {
expired = append(expired, contractQueue.Expire(minEnqueueTime)...)
if contractQueue.IsDone() {
delete(self.destinationContracts, contractKey)
}
}
}()
if 0 < len(expired) {
self.client.log.V(1).Infof("[contract]expired %d queued contracts\n", len(expired))
// close outside the manager mutex: CloseContract re-takes it
self.closeContracts(expired)
}
}
}
func (self *ContractManager) providePing() {
if self.settings.ProvidePingTimeout == 0 {
return
}
// Wait for the client to finish wiring before our first send. This
// goroutine is started from `NewContractManager`, which runs inside
// `NewClientWithTag` before `initBuffers` constructs `sendBuffer`.
// Without this gate the ping path can race the buffer wiring.
select {
case <-self.client.ReadyNotify():
case <-self.ctx.Done():
return
}
// used for logging states only
logWait := false
waitForProvide := func() bool {
for {
notify := self.provideMonitor.NotifyChannel()
var provide bool
func() {
self.mutex.Lock()
defer self.mutex.Unlock()
if self.providePaused {
provide = false
} else {
provide = self.provideModes[protocol.ProvideMode_Public] || self.provideModes[protocol.ProvideMode_PublicStream]
}
}()
if provide {
if logWait {
logWait = false
self.client.log.Infof("[contract]provide ping continue\n")
}
return true
}
if !logWait {
logWait = true
self.client.log.Infof("[contract]provide ping wait\n")
}
select {
case <-self.ctx.Done():
return false
case <-notify:
}
}
}
lastPingTime := time.Time{}
for {
if !waitForProvide() {
return
}
// uniform timeout with mean `ProvidePingTimeout`
timeout := time.Duration(mathrand.Int63n(int64(2*self.settings.ProvidePingTimeout))) - time.Now().Sub(lastPingTime)
if 0 < timeout {
select {
case <-self.ctx.Done():
return
case <-WakeupAfter(timeout, self.settings.ProvidePingTimeout):
}
} else {
select {
case <-self.ctx.Done():
return
default:
}
}
ack := make(chan error)
providePing := &protocol.ProvidePing{}
frame, err := ToFrame(providePing, self.settings.ProtocolVersion)
if err != nil {
self.client.log.Infof("[contract]could not create provide ping frame = %s", err)
return
}
self.client.SendControl(frame, func(err error) {
select {
case ack <- err:
case <-self.ctx.Done():
}
})
// wait for the ack before sending another ping
select {
case err := <-ack:
if err != nil {
self.client.log.Infof("[contract]provide ping err = %s\n", err)
}
case <-self.ctx.Done():
return
}
lastPingTime = time.Now()
}
}
func (self *ContractManager) StandardContractTransferByteCount() ByteCount {
return self.settings.StandardContractTransferByteCount
}
func (self *ContractManager) AddContractStatusCallback(contractStatusCallback ContractStatusFunction) func() {
worker := newContractStatusCallbackWorker(self.ctx, contractStatusCallback, self.settings.SequenceBufferSize)
callbackId := self.contractStatusCallbacks.Add(worker)
return func() {
self.contractStatusCallbacks.Remove(callbackId)
worker.Close()
}
}
// ContractStatusFunction
func (self *ContractManager) contractStatus(contractStatus *ContractStatus) {
for _, contractStatusCallback := range self.contractStatusCallbacks.Get() {
contractStatusCallback.Dispatch(contractStatus)
}
}
/*
// ReceiveFunction
func (self *ContractManager) Receive(source TransferPath, frames []*protocol.Frame, provideMode protocol.ProvideMode) {
if source.IsControlSource() {
for _, frame := range frames {
self.handleControlFrame(nil, frame)
}
}
}
*/
func (self *ContractManager) HandleControlFrame(contractKey ContractKey, frame *protocol.Frame) error {
switch frame.MessageType {
case protocol.MessageType_TransferCreateContractResult:
contracts, contractErrors := self.parseControlFrame(frame)
for _, contract := range contracts {
c := func() error {
var contractStatus *ContractStatus
defer func() {
if contractStatus != nil {
self.contractStatus(contractStatus)
}
}()
err := self.addContract(contractKey, contract)
if err != nil {
// contract rejected
contractError := protocol.ContractError_Trust
contractStatus = &ContractStatus{
Key: contractKey,
Error: &contractError,
}
return err
}
storedContract := &protocol.StoredContract{}
err = ProtoUnmarshal(contract.StoredContractBytes, storedContract)
if err != nil {
contractError := protocol.ContractError_Invalid
contractStatus = &ContractStatus{
Key: contractKey,
Error: &contractError,
}
return err
}
premium := false
if storedContract.Priority != nil {
premium = 0 < *storedContract.Priority
}
contractStatus = &ContractStatus{
Key: contractKey,
Premium: premium,
}
return nil
}
if self.client.log.V(2).Enabled() {
TraceWithReturn(
"[contract]add",
c,
)
} else {
c()
}
}
for _, contractError := range contractErrors {
self.client.log.V(1).Infof("[contract]error = %s\n", contractError)
c := func() {
contractStatus := &ContractStatus{
Key: contractKey,
Error: &contractError,
}
self.contractStatus(contractStatus)
}
if self.client.log.V(2).Enabled() {
Trace(
fmt.Sprintf("[contract]error = %s", contractError),
c,
)
} else {
c()
}
}
}
return nil
}
// frames are verified before calling to be from source ControlId
func (self *ContractManager) parseControlFrame(frame *protocol.Frame) (
contracts []*protocol.Contract,
contractErrors []protocol.ContractError,
) {
addResult := func(v *protocol.CreateContractResult) {
if contractError := v.Error; contractError != nil {
contractErrors = append(contractErrors, *contractError)
} else if contract := v.Contract; contract != nil {
storedContract := &protocol.StoredContract{}
err := ProtoUnmarshal(contract.StoredContractBytes, storedContract)
if err != nil {
return
}
contracts = append(contracts, contract)
}
}
switch frame.MessageType {
case protocol.MessageType_TransferCreateContractResult:
b := make([]byte, len(frame.MessageBytes))
copy(b, frame.MessageBytes)
r := &protocol.CreateContractResult{}
err := ProtoUnmarshal(b, r)
if err == nil {
addResult(r)
}
}
return
}
func (self *ContractManager) GetProvideSecretKeys() map[protocol.ProvideMode][]byte {
self.mutex.Lock()
defer self.mutex.Unlock()
return maps.Clone(self.provideSecretKeys)
}
func (self *ContractManager) LoadProvideSecretKeys(provideSecretKeys map[protocol.ProvideMode][]byte) {
self.mutex.Lock()
defer self.mutex.Unlock()
for provideMode, provideSecretKey := range provideSecretKeys {
self.provideSecretKeys[provideMode] = provideSecretKey
}
}
func (self *ContractManager) InitProvideSecretKeys() {
self.mutex.Lock()
defer self.mutex.Unlock()
for i, _ := range protocol.ProvideMode_name {
provideMode := protocol.ProvideMode(i)
provideSecretKey, ok := self.provideSecretKeys[provideMode]
if !ok {
// generate a new key
provideSecretKey = make([]byte, 32)
_, err := rand.Read(provideSecretKey)
if err != nil {
panic(err)
}
self.provideSecretKeys[provideMode] = provideSecretKey
}
}
}
func (self *ContractManager) SetProvidePaused(providePaused bool) bool {
changed := false
func() {
self.mutex.Lock()
defer self.mutex.Unlock()
if self.providePaused != providePaused {
self.providePaused = providePaused
self.provideMonitor.NotifyAll()
changed = true
}
}()
if changed {
if provideFrame, err := self.provideFrame(); err == nil && provideFrame != nil {
self.controlSyncProvide.Send(
provideFrame,
nil,
nil,
)
}
return true
}
return false
}
func (self *ContractManager) IsProvidePaused() bool {
self.mutex.Lock()
defer self.mutex.Unlock()
return self.providePaused
}
func (self *ContractManager) provideFrame() (*protocol.Frame, error) {
self.mutex.Lock()
defer self.mutex.Unlock()
var provide *protocol.Provide
if self.providePaused {
// keep only ProvideMode_Stream to allow return traffic, if set
provideKeys := []*protocol.ProvideKey{}
for provideMode, allow := range self.provideModes {
if allow && provideMode == protocol.ProvideMode_Stream {
provideSecretKey, ok := self.provideSecretKeys[provideMode]
if ok {
provideKeys = append(provideKeys, &protocol.ProvideKey{
Mode: provideMode,
ProvideSecretKey: provideSecretKey,
})
} else {
self.client.log.Infof("[contract]missing provide key for %d. Will omit.\n", provideMode)
}
}
}
provide = &protocol.Provide{
Keys: provideKeys,
}
} else {
provideKeys := []*protocol.ProvideKey{}
for provideMode, allow := range self.provideModes {
if allow {
provideSecretKey, ok := self.provideSecretKeys[provideMode]
if ok {
provideKeys = append(provideKeys, &protocol.ProvideKey{
Mode: provideMode,
ProvideSecretKey: provideSecretKey,
})
} else {
self.client.log.Infof("[contract]missing provide key for %d. Will omit.\n", provideMode)
}
}
}
provide = &protocol.Provide{
Keys: provideKeys,
}
}
provideFrame, err := ToFrame(provide, self.settings.ProtocolVersion)
if err != nil {
self.client.log.Infof("[contract]could not create provide frame = %s", err)
return nil, err
}
return provideFrame, nil
}
func (self *ContractManager) SetProvideModesWithReturnTraffic(provideModes map[protocol.ProvideMode]bool) {
self.SetProvideModesWithReturnTrafficWithAckCallback(provideModes, func(err error) {})
}
// clients must enable `ProvideMode_Stream` to allow return traffic
func (self *ContractManager) SetProvideModesWithReturnTrafficWithAckCallback(provideModes map[protocol.ProvideMode]bool, ackCallback func(err error)) {
updatedProvideModes := map[protocol.ProvideMode]bool{}
maps.Copy(updatedProvideModes, provideModes)
updatedProvideModes[protocol.ProvideMode_Stream] = true
self.SetProvideModesWithAckCallback(updatedProvideModes, ackCallback)
}
func (self *ContractManager) SetProvideModes(provideModes map[protocol.ProvideMode]bool) {
self.SetProvideModesWithAckCallback(provideModes, func(err error) {})
}
// applyProvideModes generates any missing provide secret keys and updates the
// active provide modes. The provide frame must be (re)sent afterward to register
// the change with the platform.
func (self *ContractManager) applyProvideModes(provideModes map[protocol.ProvideMode]bool) {
self.mutex.Lock()
defer self.mutex.Unlock()
// keep all keys (see note on `provideSecretKeys`)
for provideMode, allow := range provideModes {
if allow {
provideSecretKey, ok := self.provideSecretKeys[provideMode]
if !ok {
// generate a new key
provideSecretKey = make([]byte, 32)
_, err := rand.Read(provideSecretKey)
if err != nil {
panic(err)
}
self.provideSecretKeys[provideMode] = provideSecretKey
}
}
}
self.provideModes = maps.Clone(provideModes)
self.provideMonitor.NotifyAll()
}
func (self *ContractManager) SetProvideModesWithAckCallback(provideModes map[protocol.ProvideMode]bool, ackCallback func(err error)) {
self.applyProvideModes(provideModes)
if provideFrame, err := self.provideFrame(); err != nil {
ackCallback(err)
} else if provideFrame != nil {
self.controlSyncProvide.Send(
provideFrame,
nil,
ackCallback,
)
} else {
ackCallback(nil)
}
}
// SetProvideModesWithReturnTrafficWithOobAckCallback is like
// SetProvideModesWithReturnTrafficWithAckCallback, but registers the provide via
// the out-of-band control, so the ack means the platform has committed the
// provide secret (the in-band control ack only means the message was delivered).
// Use this when a caller must wait for the secret to be registered before using
// the client — e.g. the return path of a multi-client client, whose companion
// (Stream) contracts are verified against this secret.
func (self *ContractManager) SetProvideModesWithReturnTrafficWithOobAckCallback(provideModes map[protocol.ProvideMode]bool, ackCallback func(err error)) {
updatedProvideModes := map[protocol.ProvideMode]bool{}
maps.Copy(updatedProvideModes, provideModes)
updatedProvideModes[protocol.ProvideMode_Stream] = true
self.SetProvideModesWithOobAckCallback(updatedProvideModes, ackCallback)
}
func (self *ContractManager) SetProvideModesWithOobAckCallback(provideModes map[protocol.ProvideMode]bool, ackCallback func(err error)) {
self.applyProvideModes(provideModes)
if provideFrame, err := self.provideFrame(); err != nil {
ackCallback(err)
} else if provideFrame != nil {
self.controlSyncProvideOob.Send(
provideFrame,
ackCallback,
)
} else {
ackCallback(nil)
}
}
func (self *ContractManager) GetProvideModes() map[protocol.ProvideMode]bool {
self.mutex.Lock()
defer self.mutex.Unlock()
return maps.Clone(self.provideModes)
}
func (self *ContractManager) Verify(storedContractHmac []byte, storedContractBytes []byte, provideMode protocol.ProvideMode) bool {
self.mutex.Lock()
defer self.mutex.Unlock()
// only allow ProvideMode_Stream when paused, for return traffic
if self.providePaused && provideMode != protocol.ProvideMode_Stream {
return false
}
if !self.provideModes[provideMode] {
return false
}
provideSecretKey, ok := self.provideSecretKeys[provideMode]
if !ok {
// provide mode is not enabled
return false
}
return VerifyStoredContract(self.settings, provideSecretKey, storedContractBytes, storedContractHmac)
}
func (self *ContractManager) GetProvideSecretKey(provideMode protocol.ProvideMode) ([]byte, bool) {
self.mutex.Lock()
defer self.mutex.Unlock()
if !self.provideModes[provideMode] {
return nil, false
}
provideSecretKey, ok := self.provideSecretKeys[provideMode]
return provideSecretKey, ok
}
func (self *ContractManager) RequireProvideSecretKey(provideMode protocol.ProvideMode) []byte {
secretKey, ok := self.GetProvideSecretKey(provideMode)
if !ok {
panic(fmt.Errorf("Missing provide secret for %s", provideMode))
}
return secretKey
}
func (self *ContractManager) AddNoContractPeer(clientId Id) {
self.mutex.Lock()
defer self.mutex.Unlock()
self.sendNoContractClientIds[clientId] = true
self.receiveNoContractClientIds[clientId] = true
}
func (self *ContractManager) SendNoContract(destinationId Id) bool {
self.mutex.Lock()
defer self.mutex.Unlock()
if allow, ok := self.sendNoContractClientIds[destinationId]; ok {
return allow
}
if !self.settings.ContractsEnabled() {
return true
}
return false
}
func (self *ContractManager) ReceiveNoContract(sourceId Id) bool {
self.mutex.Lock()
defer self.mutex.Unlock()
if allow, ok := self.receiveNoContractClientIds[sourceId]; ok {
return allow
}
if !self.settings.ContractsEnabled() {