-
Notifications
You must be signed in to change notification settings - Fork 45
/
TokenNetwork.sol
1625 lines (1407 loc) · 61.7 KB
/
TokenNetwork.sol
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
pragma solidity ^0.4.23;
import "raiden/Token.sol";
import "raiden/Utils.sol";
import "raiden/lib/ECVerify.sol";
import "raiden/SecretRegistry.sol";
/// @title TokenNetwork
/// @notice Stores and manages all the Raiden Network channels that use the
/// token specified
/// in this TokenNetwork contract.
contract TokenNetwork is Utils {
string constant public contract_version = "0.3._";
// Instance of the token used by the channels
Token public token;
// Instance of SecretRegistry used for storing secrets revealed in a
// mediating transfer.
SecretRegistry public secret_registry;
// Chain ID as specified by EIP155 used in balance proof signatures to
// avoid replay attacks
uint256 public chain_id;
uint256 public settlement_timeout_min;
uint256 public settlement_timeout_max;
uint256 constant public MAX_SAFE_UINT256 = (
115792089237316195423570985008687907853269984665640564039457584007913129639935
);
// Bug bounty release deposit limit
uint256 public deposit_limit;
// Global, monotonically increasing counter that keeps track of all the
// opened channels in this contract
uint256 public channel_counter;
string public constant signature_prefix = '\x19Ethereum Signed Message:\n';
// channel_identifier => Channel
// channel identifier is the channel_counter value at the time of opening
// the channel
mapping (uint256 => Channel) public channels;
// This is needed to enforce one channel per pair of participants
// The key is keccak256(participant1_address, participant2_address)
mapping (bytes32 => uint256) public participants_hash_to_channel_identifier;
// We keep the unlock data in a separate mapping to allow channel data
// structures to be removed when settling uncooperatively. If there are
// locked pending transfers, we need to store data needed to unlock them at
// a later time.
// The key is `keccak256(uint256 channel_identifier, address participant,
// address partner)` Where `participant` is the participant that sent the
// pending transfers We need `partner` for knowing where to send the
// claimable tokens
mapping(bytes32 => UnlockData) private unlock_identifier_to_unlock_data;
struct Participant {
// Total amount of tokens transferred to this smart contract through
// the `setTotalDeposit` function, for a specific channel, in the
// participant's benefit.
// This is a strictly monotonic value. Note that direct token transfer
// cannot be tracked and will be burned.
uint256 deposit;
// Total amount of tokens withdrawn by the participant during the
// lifecycle of this channel.
// This is a strictly monotonic value.
uint256 withdrawn_amount;
// This is a value set to true after the channel has been closed, only
// if this is the participant who closed the channel.
bool is_the_closer;
// keccak256 of the balance data provided after a closeChannel or an
// updateNonClosingBalanceProof call
bytes32 balance_hash;
// Monotonically increasing counter of the off-chain transfers,
// provided along with the balance_hash
uint256 nonce;
}
enum ChannelState {
NonExistent, // 0
Opened, // 1
Closed, // 2
Settled, // 3; Note: The channel has at least one pending unlock
Removed // 4; Note: Channel data is removed, there are no pending unlocks
}
enum MessageTypeId {
None,
BalanceProof,
BalanceProofUpdate,
Withdraw,
CooperativeSettle
}
struct Channel {
// After opening the channel this value represents the settlement
// window. This is the number of blocks that need to be mined between
// closing the channel uncooperatively and settling the channel.
// After the channel has been uncooperatively closed, this value
// represents the block number after which settleChannel can be called.
uint256 settle_block_number;
ChannelState state;
mapping(address => Participant) participants;
}
struct SettlementData {
uint256 deposit;
uint256 withdrawn;
uint256 transferred;
uint256 locked;
}
struct UnlockData {
// Merkle root of the pending transfers tree from the Raiden client
bytes32 locksroot;
// Total amount of tokens locked in the pending transfers corresponding
// to the `locksroot`
uint256 locked_amount;
}
event ChannelOpened(
uint256 indexed channel_identifier,
address indexed participant1,
address indexed participant2,
uint256 settle_timeout
);
event ChannelNewDeposit(
uint256 indexed channel_identifier,
address indexed participant,
uint256 total_deposit
);
// total_withdraw is how much the participant has withdrawn during the
// lifetime of the channel. The actual amount which the participant withdrew
// is `total_withdraw - total_withdraw_from_previous_event_or_zero`
/* event ChannelWithdraw(
uint256 indexed channel_identifier,
address indexed participant,
uint256 total_withdraw
); */
event ChannelClosed(
uint256 indexed channel_identifier,
address indexed closing_participant,
uint256 indexed nonce
);
event ChannelUnlocked(
uint256 indexed channel_identifier,
address indexed participant,
address indexed partner,
bytes32 locksroot,
uint256 unlocked_amount,
uint256 returned_tokens
);
event NonClosingBalanceProofUpdated(
uint256 indexed channel_identifier,
address indexed closing_participant,
uint256 indexed nonce
);
event ChannelSettled(
uint256 indexed channel_identifier,
uint256 participant1_amount,
uint256 participant2_amount
);
modifier isOpen(uint256 channel_identifier) {
require(channels[channel_identifier].state == ChannelState.Opened);
_;
}
modifier settleTimeoutValid(uint256 timeout) {
require(timeout >= settlement_timeout_min);
require(timeout <= settlement_timeout_max);
_;
}
constructor(
address _token_address,
address _secret_registry,
uint256 _chain_id,
uint256 _settlement_timeout_min,
uint256 _settlement_timeout_max
)
public
{
require(_token_address != address(0x0));
require(_secret_registry != address(0x0));
require(_chain_id > 0);
require(_settlement_timeout_min > 0);
require(_settlement_timeout_max > _settlement_timeout_min);
require(contractExists(_token_address));
require(contractExists(_secret_registry));
token = Token(_token_address);
secret_registry = SecretRegistry(_secret_registry);
chain_id = _chain_id;
settlement_timeout_min = _settlement_timeout_min;
settlement_timeout_max = _settlement_timeout_max;
// Make sure the contract is indeed a token contract
require(token.totalSupply() > 0);
// Try to get token decimals, otherwise assume 18
bool exists = address(token).call(abi.encodeWithSignature("decimals()"));
uint8 decimals = 18;
if (exists) {
decimals = token.decimals();
}
deposit_limit = 100 * (10 ** uint256(decimals));
}
/// @notice Opens a new channel between `participant1` and `participant2`.
/// Can be called by anyone.
/// @param participant1 Ethereum address of a channel participant.
/// @param participant2 Ethereum address of the other channel participant.
/// @param settle_timeout Number of blocks that need to be mined between a
/// call to closeChannel and settleChannel.
function openChannel(address participant1, address participant2, uint256 settle_timeout)
settleTimeoutValid(settle_timeout)
public
returns (uint256)
{
bytes32 pair_hash;
uint256 channel_identifier;
// First increment the counter
// There will never be a channel with channel_identifier == 0
channel_counter += 1;
channel_identifier = channel_counter;
pair_hash = getParticipantsHash(participant1, participant2);
// There must only be one channel opened between two participants at
// any moment in time.
require(participants_hash_to_channel_identifier[pair_hash] == 0);
participants_hash_to_channel_identifier[pair_hash] = channel_identifier;
Channel storage channel = channels[channel_identifier];
// We always increase the channel counter, therefore no channel data can already exist,
// corresponding to this channel_identifier. This check must never fail.
assert(channel.settle_block_number == 0);
assert(channel.state == ChannelState.NonExistent);
// Store channel information
channel.settle_block_number = settle_timeout;
channel.state = ChannelState.Opened;
emit ChannelOpened(
channel_identifier,
participant1,
participant2,
settle_timeout
);
return channel_identifier;
}
/// @notice Sets the channel participant total deposit value.
/// Can be called by anyone.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant Channel participant whose deposit is being set.
/// @param total_deposit The total amount of tokens that the participant
/// will have as a deposit.
/// @param partner Channel partner address, needed to compute the total
/// channel deposit.
function setTotalDeposit(
uint256 channel_identifier,
address participant,
uint256 total_deposit,
address partner
)
isOpen(channel_identifier)
public
{
require(channel_identifier == getChannelIdentifier(participant, partner));
require(total_deposit > 0);
require(total_deposit <= deposit_limit);
uint256 added_deposit;
uint256 channel_deposit;
Channel storage channel = channels[channel_identifier];
Participant storage participant_state = channel.participants[participant];
Participant storage partner_state = channel.participants[partner];
// Calculate the actual amount of tokens that will be transferred
added_deposit = total_deposit - participant_state.deposit;
// The actual amount of tokens that will be transferred must be > 0
require(added_deposit > 0);
// Underflow check; we use <= because added_deposit == total_deposit for the first deposit
require(added_deposit <= total_deposit);
// This should never fail at this point. Added check for security, because we directly set
// the participant_state.deposit = total_deposit, while we transfer `added_deposit` tokens.
assert(participant_state.deposit + added_deposit == total_deposit);
// Update the participant's channel deposit
participant_state.deposit = total_deposit;
// Calculate the entire channel deposit, to avoid overflow
channel_deposit = participant_state.deposit + partner_state.deposit;
// Overflow check
require(channel_deposit >= participant_state.deposit);
emit ChannelNewDeposit(
channel_identifier,
participant,
participant_state.deposit
);
// Do the transfer
require(token.transferFrom(msg.sender, address(this), added_deposit));
}
/* /// @notice Allows `participant` to withdraw tokens from the channel that he
/// has with `partner`, without closing it. Can be called by anyone. Can
/// only be called once per each signed withdraw message.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant Channel participant, who will receive the withdrawn
/// amount.
/// @param total_withdraw Total amount of tokens that are marked as
/// withdrawn from the channel during the channel lifecycle.
/// @param participant_signature Participant's signature on the withdraw
/// data.
/// @param partner_signature Partner's signature on the withdraw data.
function setTotalWithdraw(
uint256 channel_identifier,
address participant,
uint256 total_withdraw,
bytes participant_signature,
bytes partner_signature
)
isOpen(channel_identifier)
external
{
uint256 total_deposit;
uint256 current_withdraw;
address partner;
require(total_withdraw > 0);
// Authenticate both channel partners via there signatures:
require(participant == recoverAddressFromWithdrawMessage(
channel_identifier,
participant,
total_withdraw,
participant_signature
));
partner = recoverAddressFromWithdrawMessage(
channel_identifier,
participant,
total_withdraw,
partner_signature
);
// Validate that authenticated partners and the channel identifier match
require(channel_identifier == getChannelIdentifier(participant, partner));
// Read channel state after validating the function input
Channel storage channel = channels[channel_identifier];
Participant storage participant_state = channel.participants[participant];
Participant storage partner_state = channel.participants[partner];
total_deposit = participant_state.deposit + partner_state.deposit;
// Entire withdrawn amount must not be bigger than the current channel deposit
require((total_withdraw + partner_state.withdrawn_amount) <= total_deposit);
require(total_withdraw <= (total_withdraw + partner_state.withdrawn_amount));
// Using the total_withdraw (monotonically increasing) in the signed
// message ensures that we do not allow replay attack to happen, by
// using the same withdraw proof twice.
// Next two lines enforce the monotonicity of total_withdraw and check for an underflow:
// (we use <= because current_withdraw == total_withdraw for the first withdraw)
current_withdraw = total_withdraw - participant_state.withdrawn_amount;
require(current_withdraw <= total_withdraw);
// The actual amount of tokens that will be transferred must be > 0 to disable the reuse of
// withdraw messages completely.
require(current_withdraw > 0);
// This should never fail at this point. Added check for security, because we directly set
// the participant_state.withdrawn_amount = total_withdraw,
// while we transfer `current_withdraw` tokens.
assert(participant_state.withdrawn_amount + current_withdraw == total_withdraw);
emit ChannelWithdraw(
channel_identifier,
participant,
total_withdraw
);
// Do the state change and tokens transfer
participant_state.withdrawn_amount = total_withdraw;
require(token.transfer(participant, current_withdraw));
// This should never happen, as we have an overflow check in setTotalDeposit
assert(total_deposit >= participant_state.deposit);
assert(total_deposit >= partner_state.deposit);
// A withdraw should never happen if a participant already has a
// balance proof in storage. This should never fail as we use isOpen.
assert(participant_state.nonce == 0);
assert(partner_state.nonce == 0);
} */
/// @notice Close the channel defined by the two participant addresses. Only
/// a participant may close the channel, providing a balance proof signed by
/// its partner. Callable only once.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param partner Channel partner of the `msg.sender`, who provided the
/// signature.
/// @param balance_hash Hash of (transferred_amount, locked_amount,
/// locksroot).
/// @param additional_hash Computed from the message. Used for message
/// authentication.
/// @param nonce Strictly monotonic value used to order transfers.
/// @param signature Partner's signature of the balance proof data.
function closeChannel(
uint256 channel_identifier,
address partner,
bytes32 balance_hash,
uint256 nonce,
bytes32 additional_hash,
bytes signature
)
isOpen(channel_identifier)
public
{
require(channel_identifier == getChannelIdentifier(msg.sender, partner));
address recovered_partner_address;
Channel storage channel = channels[channel_identifier];
channel.state = ChannelState.Closed;
channel.participants[msg.sender].is_the_closer = true;
// This is the block number at which the channel can be settled.
channel.settle_block_number += uint256(block.number);
// Nonce 0 means that the closer never received a transfer, therefore
// never received a balance proof, or he is intentionally not providing
// the latest transfer, in which case the closing party is going to
// lose the tokens that were transferred to him.
if (nonce > 0) {
recovered_partner_address = recoverAddressFromBalanceProof(
channel_identifier,
balance_hash,
nonce,
additional_hash,
signature
);
// Signature must be from the channel partner
require(partner == recovered_partner_address);
updateBalanceProofData(
channel,
recovered_partner_address,
nonce,
balance_hash
);
}
emit ChannelClosed(channel_identifier, msg.sender, nonce);
}
/// @notice Called on a closed channel, the function allows the non-closing
/// participant to provide the last balance proof, which modifies the
/// closing participant's state. Can be called multiple times by anyone.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param closing_participant Channel participant who closed the channel.
/// @param non_closing_participant Channel participant who needs to update
/// the balance proof.
/// @param balance_hash Hash of (transferred_amount, locked_amount,
/// locksroot).
/// @param additional_hash Computed from the message. Used for message
/// authentication.
/// @param nonce Strictly monotonic value used to order transfers.
/// @param closing_signature Closing participant's signature of the balance
/// proof data.
/// @param non_closing_signature Non-closing participant signature of the
/// balance proof data.
function updateNonClosingBalanceProof(
uint256 channel_identifier,
address closing_participant,
address non_closing_participant,
bytes32 balance_hash,
uint256 nonce,
bytes32 additional_hash,
bytes closing_signature,
bytes non_closing_signature
)
external
{
require(channel_identifier == getChannelIdentifier(
closing_participant,
non_closing_participant
));
require(balance_hash != bytes32(0x0));
require(nonce > 0);
address recovered_non_closing_participant;
address recovered_closing_participant;
Channel storage channel = channels[channel_identifier];
require(channel.state == ChannelState.Closed);
// Channel must be in the settlement window
require(channel.settle_block_number >= block.number);
// We need the signature from the non-closing participant to allow
// anyone to make this transaction. E.g. a monitoring service.
recovered_non_closing_participant = recoverAddressFromBalanceProofUpdateMessage(
channel_identifier,
balance_hash,
nonce,
additional_hash,
closing_signature,
non_closing_signature
);
require(non_closing_participant == recovered_non_closing_participant);
recovered_closing_participant = recoverAddressFromBalanceProof(
channel_identifier,
balance_hash,
nonce,
additional_hash,
closing_signature
);
require(closing_participant == recovered_closing_participant);
Participant storage closing_participant_state = channel.participants[closing_participant];
// Make sure the first signature is from the closing participant
require(closing_participant_state.is_the_closer);
// Update the balance proof data for the closing_participant
updateBalanceProofData(channel, closing_participant, nonce, balance_hash);
emit NonClosingBalanceProofUpdated(
channel_identifier,
closing_participant,
nonce
);
}
/// @notice Settles the balance between the two parties. Note that arguments
/// order counts: `participant1_transferred_amount +
/// participant1_locked_amount` <= `participant2_transferred_amount +
/// participant2_locked_amount`
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant1 Channel participant.
/// @param participant1_transferred_amount The latest known amount of tokens
/// transferred from `participant1` to `participant2`.
/// @param participant1_locked_amount Amount of tokens owed by
/// `participant1` to `participant2`, contained in locked transfers that
/// will be retrieved by calling `unlock` after the channel is settled.
/// @param participant1_locksroot The latest known merkle root of the
/// pending hash-time locks of `participant1`, used to validate the unlocked
/// proofs.
/// @param participant2 Other channel participant.
/// @param participant2_transferred_amount The latest known amount of tokens
/// transferred from `participant2` to `participant1`.
/// @param participant2_locked_amount Amount of tokens owed by
/// `participant2` to `participant1`, contained in locked transfers that
/// will be retrieved by calling `unlock` after the channel is settled.
/// @param participant2_locksroot The latest known merkle root of the
/// pending hash-time locks of `participant2`, used to validate the unlocked
/// proofs.
function settleChannel(
uint256 channel_identifier,
address participant1,
uint256 participant1_transferred_amount,
uint256 participant1_locked_amount,
bytes32 participant1_locksroot,
address participant2,
uint256 participant2_transferred_amount,
uint256 participant2_locked_amount,
bytes32 participant2_locksroot
)
public
{
// There are several requirements that this function MUST enforce:
// - it MUST never fail; therefore, any overflows or underflows must be
// handled gracefully
// - it MUST ensure that if participants use the latest valid balance proofs,
// provided by the official Raiden client, the participants will be able
// to receive correct final balances at the end of the channel lifecycle
// - it MUST ensure that the participants cannot cheat by providing an
// old, valid balance proof of their partner; meaning that their partner MUST
// receive at least the amount of tokens that he would have received if
// the latest valid balance proofs are used.
// - the contract cannot determine if a balance proof is invalid (values
// are not within the constraints enforced by the official Raiden client),
// therefore it cannot ensure correctness. Users MUST use the official
// Raiden clients for signing balance proofs.
require(channel_identifier == getChannelIdentifier(participant1, participant2));
bytes32 pair_hash;
pair_hash = getParticipantsHash(participant1, participant2);
Channel storage channel = channels[channel_identifier];
require(channel.state == ChannelState.Closed);
// Settlement window must be over
require(channel.settle_block_number < block.number);
Participant storage participant1_state = channel.participants[participant1];
Participant storage participant2_state = channel.participants[participant2];
require(verifyBalanceHashData(
participant1_state,
participant1_transferred_amount,
participant1_locked_amount,
participant1_locksroot
));
require(verifyBalanceHashData(
participant2_state,
participant2_transferred_amount,
participant2_locked_amount,
participant2_locksroot
));
// We are calculating the final token amounts that need to be
// transferred to the participants now and the amount of tokens that
// need to remain locked in the contract. These tokens can be unlocked
// by calling `unlock`.
// participant1_transferred_amount = the amount of tokens that
// participant1 will receive in this transaction.
// participant2_transferred_amount = the amount of tokens that
// participant2 will receive in this transaction.
// participant1_locked_amount = the amount of tokens remaining in the
// contract, representing pending transfers from participant1 to participant2.
// participant2_locked_amount = the amount of tokens remaining in the
// contract, representing pending transfers from participant2 to participant1.
// We are reusing variables due to the local variables number limit.
// For better readability this can be refactored further.
(
participant1_transferred_amount,
participant2_transferred_amount,
participant1_locked_amount,
participant2_locked_amount
) = getSettleTransferAmounts(
participant1_state,
participant1_transferred_amount,
participant1_locked_amount,
participant2_state,
participant2_transferred_amount,
participant2_locked_amount
);
// Remove the channel data from storage
delete channel.participants[participant1];
delete channel.participants[participant2];
delete channels[channel_identifier];
// Remove the pair's channel counter
delete participants_hash_to_channel_identifier[pair_hash];
// Store balance data needed for `unlock`, including the calculated
// locked amounts remaining in the contract.
storeUnlockData(
channel_identifier,
participant1,
participant2,
participant1_locked_amount,
participant1_locksroot
);
storeUnlockData(
channel_identifier,
participant2,
participant1,
participant2_locked_amount,
participant2_locksroot
);
emit ChannelSettled(
channel_identifier,
participant1_transferred_amount,
participant2_transferred_amount
);
// Do the actual token transfers
if (participant1_transferred_amount > 0) {
require(token.transfer(participant1, participant1_transferred_amount));
}
if (participant2_transferred_amount > 0) {
require(token.transfer(participant2, participant2_transferred_amount));
}
}
/// @notice Unlocks all pending off-chain transfers from `partner` to
/// `participant` and sends the locked tokens corresponding to locks with
/// secrets registered on-chain to the `participant`. Locked tokens
/// corresponding to locks where the secret was not revelead on-chain will
/// return to the `partner`. Anyone can call unlock.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant Address who will receive the claimable unlocked
/// tokens.
/// @param partner Address who sent the pending transfers and will receive
/// the unclaimable unlocked tokens.
/// @param merkle_tree_leaves The entire merkle tree of pending transfers
/// that `partner` sent to `participant`.
function unlock(
uint256 channel_identifier,
address participant,
address partner,
bytes merkle_tree_leaves
)
public
{
// Channel represented by channel_identifier must be settled and
// channel data deleted
require(channel_identifier != getChannelIdentifier(participant, partner));
// After the channel is settled the storage is cleared, therefore the
// value will be NonExistent and not Settled. The value Settled is used
// for the external APIs
require(channels[channel_identifier].state == ChannelState.NonExistent);
require(merkle_tree_leaves.length > 0);
bytes32 unlock_key;
bytes32 computed_locksroot;
uint256 unlocked_amount;
uint256 locked_amount;
uint256 returned_tokens;
// Calculate the locksroot for the pending transfers and the amount of
// tokens corresponding to the locked transfers with secrets revealed
// on chain.
(computed_locksroot, unlocked_amount) = getMerkleRootAndUnlockedAmount(
merkle_tree_leaves
);
// The partner must have a non-empty locksroot on-chain that must be
// the same as the computed locksroot.
// Get the amount of tokens that have been left in the contract, to
// account for the pending transfers `partner` -> `participant`.
unlock_key = getUnlockIdentifier(channel_identifier, partner, participant);
UnlockData storage unlock_data = unlock_identifier_to_unlock_data[unlock_key];
locked_amount = unlock_data.locked_amount;
// Locksroot must be the same as the computed locksroot
require(unlock_data.locksroot == computed_locksroot);
// There are no pending transfers if the locked_amount is 0.
// Transaction must fail
require(locked_amount > 0);
// Make sure we don't transfer more tokens than previously reserved in
// the smart contract.
unlocked_amount = min(unlocked_amount, locked_amount);
// Transfer the rest of the tokens back to the partner
returned_tokens = locked_amount - unlocked_amount;
// Remove partner's unlock data
delete unlock_identifier_to_unlock_data[unlock_key];
emit ChannelUnlocked(
channel_identifier,
participant,
partner,
computed_locksroot,
unlocked_amount,
returned_tokens
);
// Transfer the unlocked tokens to the participant. unlocked_amount can
// be 0
if (unlocked_amount > 0) {
require(token.transfer(participant, unlocked_amount));
}
// Transfer the rest of the tokens back to the partner
if (returned_tokens > 0) {
require(token.transfer(partner, returned_tokens));
}
// At this point, this should always be true
assert(locked_amount >= returned_tokens);
assert(locked_amount >= unlocked_amount);
}
/* /// @notice Cooperatively settles the balances between the two channel
/// participants and transfers the agreed upon token amounts to the
/// participants. After this the channel lifecycle has ended and no more
/// operations can be done on it.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant1_address Address of channel participant.
/// @param participant1_balance Amount of tokens that `participant1_address`
/// must receive when the channel is settled and removed.
/// @param participant2_address Address of the other channel participant.
/// @param participant2_balance Amount of tokens that `participant2_address`
/// must receive when the channel is settled and removed.
/// @param participant1_signature Signature of `participant1_address` on the
/// cooperative settle message.
/// @param participant2_signature Signature of `participant2_address` on the
/// cooperative settle message.
function cooperativeSettle(
uint256 channel_identifier,
address participant1_address,
uint256 participant1_balance,
address participant2_address,
uint256 participant2_balance,
bytes participant1_signature,
bytes participant2_signature
)
public
{
require(channel_identifier == getChannelIdentifier(
participant1_address,
participant2_address
));
bytes32 pair_hash;
address participant1;
address participant2;
uint256 total_available_deposit;
pair_hash = getParticipantsHash(participant1_address, participant2_address);
Channel storage channel = channels[channel_identifier];
require(channel.state == ChannelState.Opened);
participant1 = recoverAddressFromCooperativeSettleSignature(
channel_identifier,
participant1_address,
participant1_balance,
participant2_address,
participant2_balance,
participant1_signature
);
// The provided address must be the same as the recovered one
require(participant1 == participant1_address);
participant2 = recoverAddressFromCooperativeSettleSignature(
channel_identifier,
participant1_address,
participant1_balance,
participant2_address,
participant2_balance,
participant2_signature
);
// The provided address must be the same as the recovered one
require(participant2 == participant2_address);
Participant storage participant1_state = channel.participants[participant1];
Participant storage participant2_state = channel.participants[participant2];
total_available_deposit = getChannelAvailableDeposit(
participant1_state,
participant2_state
);
// The sum of the provided balances must be equal to the total
// available deposit
require(total_available_deposit == (participant1_balance + participant2_balance));
// Overflow check for the balances addition from the above check.
// This overflow should never happen if the token.transfer function is implemented
// correctly. We do not control the token implementation, therefore we add this
// check for safety.
require(participant1_balance <= participant1_balance + participant2_balance);
// Remove channel data from storage before doing the token transfers
delete channel.participants[participant1];
delete channel.participants[participant2];
delete channels[channel_identifier];
// Remove the pair's channel counter
delete participants_hash_to_channel_identifier[pair_hash];
emit ChannelSettled(channel_identifier, participant1_balance, participant2_balance);
// Do the token transfers
if (participant1_balance > 0) {
require(token.transfer(participant1, participant1_balance));
}
if (participant2_balance > 0) {
require(token.transfer(participant2, participant2_balance));
}
} */
/// @notice Returns the unique identifier for the channel given by the
/// contract.
/// @param participant Address of a channel participant.
/// @param partner Address of the other channel participant.
/// @return Unique identifier for the channel. It can be 0 if channel does
/// not exist.
function getChannelIdentifier(address participant, address partner)
view
public
returns (uint256)
{
require(participant != address(0x0));
require(partner != address(0x0));
require(participant != partner);
bytes32 pair_hash = getParticipantsHash(participant, partner);
return participants_hash_to_channel_identifier[pair_hash];
}
/// @dev Returns the channel specific data.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant1 Address of a channel participant.
/// @param participant2 Address of the other channel participant.
/// @return Channel settle_block_number and state.
function getChannelInfo(
uint256 channel_identifier,
address participant1,
address participant2
)
view
external
returns (uint256, ChannelState)
{
bytes32 unlock_key1;
bytes32 unlock_key2;
Channel storage channel = channels[channel_identifier];
ChannelState state = channel.state; // This must **not** update the storage
if (state == ChannelState.NonExistent &&
channel_identifier > 0 &&
channel_identifier <= channel_counter
) {
// The channel has been settled, channel data is removed Therefore,
// the channel state in storage is actually `0`, or `NonExistent`
// However, for this view function, we return `Settled`, in order
// to provide a consistent external API
state = ChannelState.Settled;
// We might still have data stored for future unlock operations
// Only if we do not, we can consider the channel as `Removed`
unlock_key1 = getUnlockIdentifier(channel_identifier, participant1, participant2);
UnlockData storage unlock_data1 = unlock_identifier_to_unlock_data[unlock_key1];
unlock_key2 = getUnlockIdentifier(channel_identifier, participant2, participant1);
UnlockData storage unlock_data2 = unlock_identifier_to_unlock_data[unlock_key2];
if (unlock_data1.locked_amount == 0 && unlock_data2.locked_amount == 0) {
state = ChannelState.Removed;
}
}
return (
channel.settle_block_number,
state
);
}
/// @dev Returns the channel specific data.
/// @param channel_identifier Identifier for the channel on which this
/// operation takes place.
/// @param participant Address of the channel participant whose data will be
/// returned.
/// @param partner Address of the channel partner.
/// @return Participant's deposit, withdrawn_amount, whether the participant
/// has called `closeChannel` or not, balance_hash, nonce, locksroot,
/// locked_amount.
function getChannelParticipantInfo(
uint256 channel_identifier,
address participant,
address partner
)
view
external
returns (uint256, uint256, bool, bytes32, uint256, bytes32, uint256)
{
bytes32 unlock_key;