-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSpankchainLedgerChannel.sol
1314 lines (1183 loc) · 42.7 KB
/
SpankchainLedgerChannel.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
/**
*Submitted for verification at Etherscan.io on 2018-10-06
*/
pragma solidity ^0.4.23;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
contract Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner)
public
constant
returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value)
public
returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value)
public
returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
library ECTools {
// @dev Recovers the address which has signed a message
// @thanks https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
function recoverSigner(bytes32 _hashedMsg, string _sig)
public
pure
returns (address)
{
require(_hashedMsg != 0x00);
// need this for test RPC
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg));
if (bytes(_sig).length != 132) {
return 0x0;
}
bytes32 r;
bytes32 s;
uint8 v;
bytes memory sig = hexstrToBytes(substring(_sig, 2, 132));
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v < 27 || v > 28) {
return 0x0;
}
return ecrecover(prefixedHash, v, r, s);
}
// @dev Verifies if the message is signed by an address
function isSignedBy(
bytes32 _hashedMsg,
string _sig,
address _addr
) public pure returns (bool) {
require(_addr != 0x0);
return _addr == recoverSigner(_hashedMsg, _sig);
}
// @dev Converts an hexstring to bytes
function hexstrToBytes(string _hexstr) public pure returns (bytes) {
uint256 len = bytes(_hexstr).length;
require(len % 2 == 0);
bytes memory bstr = bytes(new string(len / 2));
uint256 k = 0;
string memory s;
string memory r;
for (uint256 i = 0; i < len; i += 2) {
s = substring(_hexstr, i, i + 1);
r = substring(_hexstr, i + 1, i + 2);
uint256 p = parseInt16Char(s) * 16 + parseInt16Char(r);
bstr[k++] = uintToBytes32(p)[31];
}
return bstr;
}
// @dev Parses a hexchar, like 'a', and returns its hex value, in this case 10
function parseInt16Char(string _char) public pure returns (uint256) {
bytes memory bresult = bytes(_char);
// bool decimals = false;
if ((bresult[0] >= 48) && (bresult[0] <= 57)) {
return uint256(bresult[0]) - 48;
} else if ((bresult[0] >= 65) && (bresult[0] <= 70)) {
return uint256(bresult[0]) - 55;
} else if ((bresult[0] >= 97) && (bresult[0] <= 102)) {
return uint256(bresult[0]) - 87;
} else {
revert();
}
}
// @dev Converts a uint to a bytes32
// @thanks https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity
function uintToBytes32(uint256 _uint) public pure returns (bytes b) {
b = new bytes(32);
assembly {
mstore(add(b, 32), _uint)
}
}
// @dev Hashes the signed message
// @ref https://github.com/ethereum/go-ethereum/issues/3731#issuecomment-293866868
function toEthereumSignedMessage(string _msg)
public
pure
returns (bytes32)
{
uint256 len = bytes(_msg).length;
require(len > 0);
bytes memory prefix = "\x19Ethereum Signed Message:\n";
return keccak256(abi.encodePacked(prefix, uintToString(len), _msg));
}
// @dev Converts a uint in a string
function uintToString(uint256 _uint) public pure returns (string str) {
uint256 len = 0;
uint256 m = _uint + 0;
while (m != 0) {
len++;
m /= 10;
}
bytes memory b = new bytes(len);
uint256 i = len - 1;
while (_uint != 0) {
uint256 remainder = _uint % 10;
_uint = _uint / 10;
b[i--] = bytes1(48 + remainder);
}
str = string(b);
}
// @dev extract a substring
// @thanks https://ethereum.stackexchange.com/questions/31457/substring-in-solidity
function substring(
string _str,
uint256 _startIndex,
uint256 _endIndex
) public pure returns (string) {
bytes memory strBytes = bytes(_str);
require(_startIndex <= _endIndex);
require(_startIndex >= 0);
require(_endIndex <= strBytes.length);
bytes memory result = new bytes(_endIndex - _startIndex);
for (uint256 i = _startIndex; i < _endIndex; i++) {
result[i - _startIndex] = strBytes[i];
}
return string(result);
}
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value)
public
returns (bool success)
{
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(
balances[_from] >= _value && allowed[_from][msg.sender] >= _value
);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner)
public
constant
returns (uint256 balance)
{
return balances[_owner];
}
function approve(address _spender, uint256 _value)
public
returns (bool success)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
}
contract HumanStandardToken is StandardToken {
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = "H0.1"; //human 0.1 standard. Just an arbitrary versioning scheme.
constructor(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(
address _spender,
uint256 _value,
bytes _extraData
) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
require(
_spender.call(
bytes4(
bytes32(
keccak256(
"receiveApproval(address,uint256,address,bytes)"
)
)
),
msg.sender,
_value,
this,
_extraData
)
);
return true;
}
}
contract SpankchainLedgerChannel {
/************************************************************************************/
// YOLO inlining of the ECTools lib ¯\_(ツ)_/¯
// @dev Recovers the address which has signed a message
// @thanks https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
function recoverSigner(bytes32 _hashedMsg, string _sig)
public
pure
returns (address)
{
require(_hashedMsg != 0x00);
// need this for test RPC
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg));
if (bytes(_sig).length != 132) {
return 0x0;
}
bytes32 r;
bytes32 s;
uint8 v;
bytes memory sig = hexstrToBytes(substring(_sig, 2, 132));
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v < 27 || v > 28) {
return 0x0;
}
return ecrecover(prefixedHash, v, r, s);
}
// @dev Verifies if the message is signed by an address
function isSignedBy(
bytes32 _hashedMsg,
string _sig,
address _addr
) public pure returns (bool) {
require(_addr != 0x0);
return _addr == recoverSigner(_hashedMsg, _sig);
}
// @dev Converts an hexstring to bytes
function hexstrToBytes(string _hexstr) public pure returns (bytes) {
uint256 len = bytes(_hexstr).length;
require(len % 2 == 0);
bytes memory bstr = bytes(new string(len / 2));
uint256 k = 0;
string memory s;
string memory r;
for (uint256 i = 0; i < len; i += 2) {
s = substring(_hexstr, i, i + 1);
r = substring(_hexstr, i + 1, i + 2);
uint256 p = parseInt16Char(s) * 16 + parseInt16Char(r);
bstr[k++] = uintToBytes32(p)[31];
}
return bstr;
}
// @dev Parses a hexchar, like 'a', and returns its hex value, in this case 10
function parseInt16Char(string _char) public pure returns (uint256) {
bytes memory bresult = bytes(_char);
// bool decimals = false;
if ((bresult[0] >= 48) && (bresult[0] <= 57)) {
return uint256(bresult[0]) - 48;
} else if ((bresult[0] >= 65) && (bresult[0] <= 70)) {
return uint256(bresult[0]) - 55;
} else if ((bresult[0] >= 97) && (bresult[0] <= 102)) {
return uint256(bresult[0]) - 87;
} else {
revert();
}
}
// @dev Converts a uint to a bytes32
// @thanks https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity
function uintToBytes32(uint256 _uint) public pure returns (bytes b) {
b = new bytes(32);
assembly {
mstore(add(b, 32), _uint)
}
}
// @dev Hashes the signed message
// @ref https://github.com/ethereum/go-ethereum/issues/3731#issuecomment-293866868
function toEthereumSignedMessage(string _msg)
public
pure
returns (bytes32)
{
uint256 len = bytes(_msg).length;
require(len > 0);
bytes memory prefix = "\x19Ethereum Signed Message:\n";
return keccak256(abi.encodePacked(prefix, uintToString(len), _msg));
}
// @dev Converts a uint in a string
function uintToString(uint256 _uint) public pure returns (string str) {
uint256 len = 0;
uint256 m = _uint + 0;
while (m != 0) {
len++;
m /= 10;
}
bytes memory b = new bytes(len);
uint256 i = len - 1;
while (_uint != 0) {
uint256 remainder = _uint % 10;
_uint = _uint / 10;
b[i--] = bytes1(48 + remainder);
}
str = string(b);
}
// @dev extract a substring
// @thanks https://ethereum.stackexchange.com/questions/31457/substring-in-solidity
function substring(
string _str,
uint256 _startIndex,
uint256 _endIndex
) public pure returns (string) {
bytes memory strBytes = bytes(_str);
require(_startIndex <= _endIndex);
require(_startIndex >= 0);
require(_endIndex <= strBytes.length);
bytes memory result = new bytes(_endIndex - _startIndex);
for (uint256 i = _startIndex; i < _endIndex; i++) {
result[i - _startIndex] = strBytes[i];
}
return string(result);
}
// end of YOLO inlining
/************************************************************************************/
string public constant NAME = "Ledger Channel";
string public constant VERSION = "0.0.1";
uint256 public numChannels = 0;
event DidLCOpen(
bytes32 indexed channelId,
address indexed partyA,
address indexed partyI,
uint256 ethBalanceA,
address token,
uint256 tokenBalanceA,
uint256 LCopenTimeout
);
event DidLCJoin(
bytes32 indexed channelId,
uint256 ethBalanceI,
uint256 tokenBalanceI
);
event DidLCDeposit(
bytes32 indexed channelId,
address indexed recipient,
uint256 deposit,
bool isToken
);
event DidLCUpdateState(
bytes32 indexed channelId,
uint256 sequence,
uint256 numOpenVc,
uint256 ethBalanceA,
uint256 tokenBalanceA,
uint256 ethBalanceI,
uint256 tokenBalanceI,
bytes32 vcRoot,
uint256 updateLCtimeout
);
event DidLCClose(
bytes32 indexed channelId,
uint256 sequence,
uint256 ethBalanceA,
uint256 tokenBalanceA,
uint256 ethBalanceI,
uint256 tokenBalanceI
);
event DidVCInit(
bytes32 indexed lcId,
bytes32 indexed vcId,
bytes proof,
uint256 sequence,
address partyA,
address partyB,
uint256 balanceA,
uint256 balanceB
);
event DidVCSettle(
bytes32 indexed lcId,
bytes32 indexed vcId,
uint256 updateSeq,
uint256 updateBalA,
uint256 updateBalB,
address challenger,
uint256 updateVCtimeout
);
event DidVCClose(
bytes32 indexed lcId,
bytes32 indexed vcId,
uint256 balanceA,
uint256 balanceB
);
struct Channel {
//TODO: figure out if it's better just to split arrays by balances/deposits instead of eth/erc20
address[2] partyAddresses; // 0: partyA 1: partyI
uint256[4] ethBalances; // 0: balanceA 1:balanceI 2:depositedA 3:depositedI
uint256[4] erc20Balances; // 0: balanceA 1:balanceI 2:depositedA 3:depositedI
uint256[2] initialDeposit; // 0: eth 1: tokens
uint256 sequence;
uint256 confirmTime;
bytes32 VCrootHash;
uint256 LCopenTimeout;
uint256 updateLCtimeout; // when update LC times out
bool isOpen; // true when both parties have joined
bool isUpdateLCSettling;
uint256 numOpenVC;
HumanStandardToken token;
}
// virtual-channel state
struct VirtualChannel {
bool isClose;
bool isInSettlementState;
uint256 sequence;
address challenger; // Initiator of challenge
uint256 updateVCtimeout; // when update VC times out
// channel state
address partyA; // VC participant A
address partyB; // VC participant B
address partyI; // LC hub
uint256[2] ethBalances;
uint256[2] erc20Balances;
uint256[2] bond;
HumanStandardToken token;
}
mapping(bytes32 => VirtualChannel) public virtualChannels;
mapping(bytes32 => Channel) public Channels;
function createChannel(
bytes32 _lcID,
address _partyI,
uint256 _confirmTime,
address _token,
uint256[2] _balances // [eth, token]
) public payable {
require(
Channels[_lcID].partyAddresses[0] == address(0),
"Channel has already been created."
);
require(_partyI != 0x0, "No partyI address provided to LC creation");
require(
_balances[0] >= 0 && _balances[1] >= 0,
"Balances cannot be negative"
);
// Set initial ledger channel state
// Alice must execute this and we assume the initial state
// to be signed from this requirement
// Alternative is to check a sig as in joinChannel
Channels[_lcID].partyAddresses[0] = msg.sender;
Channels[_lcID].partyAddresses[1] = _partyI;
if (_balances[0] != 0) {
require(
msg.value == _balances[0],
"Eth balance does not match sent value"
);
Channels[_lcID].ethBalances[0] = msg.value;
}
if (_balances[1] != 0) {
Channels[_lcID].token = HumanStandardToken(_token);
require(
Channels[_lcID].token.transferFrom(
msg.sender,
this,
_balances[1]
),
"CreateChannel: token transfer failure"
);
Channels[_lcID].erc20Balances[0] = _balances[1];
}
Channels[_lcID].sequence = 0;
Channels[_lcID].confirmTime = _confirmTime;
// is close flag, lc state sequence, number open vc, vc root hash, partyA...
//Channels[_lcID].stateHash = keccak256(uint256(0), uint256(0), uint256(0), bytes32(0x0), bytes32(msg.sender), bytes32(_partyI), balanceA, balanceI);
Channels[_lcID].LCopenTimeout = now + _confirmTime;
Channels[_lcID].initialDeposit = _balances;
emit DidLCOpen(
_lcID,
msg.sender,
_partyI,
_balances[0],
_token,
_balances[1],
Channels[_lcID].LCopenTimeout
);
}
function LCOpenTimeout(bytes32 _lcID) public {
require(
msg.sender == Channels[_lcID].partyAddresses[0] &&
Channels[_lcID].isOpen == false
);
require(now > Channels[_lcID].LCopenTimeout);
// make a local copy before deleting
Channel memory channel = Channels[_lcID];
// only safe to delete since no action was taken on this channel
delete Channels[_lcID];
// transfer
if (channel.initialDeposit[0] != 0) {
channel.partyAddresses[0].transfer(
channel.ethBalances[0]
);
}
if (channel.initialDeposit[1] != 0) {
require(
channel.token.transfer(
channel.partyAddresses[0],
channel.erc20Balances[0]
),
"CreateChannel: token transfer failure"
);
}
emit DidLCClose(
_lcID,
0,
Channels[_lcID].ethBalances[0],
Channels[_lcID].erc20Balances[0],
0,
0
);
}
function joinChannel(bytes32 _lcID, uint256[2] _balances) public payable {
// require the channel is not open yet
require(Channels[_lcID].isOpen == false);
require(msg.sender == Channels[_lcID].partyAddresses[1]);
if (_balances[0] != 0) {
require(
msg.value == _balances[0],
"state balance does not match sent value"
);
Channels[_lcID].ethBalances[1] = msg.value;
}
if (_balances[1] != 0) {
require(
Channels[_lcID].token.transferFrom(
msg.sender,
this,
_balances[1]
),
"joinChannel: token transfer failure"
);
Channels[_lcID].erc20Balances[1] = _balances[1];
}
Channels[_lcID].initialDeposit[0] += _balances[0];
Channels[_lcID].initialDeposit[1] += _balances[1];
// no longer allow joining functions to be called
Channels[_lcID].isOpen = true;
numChannels++;
emit DidLCJoin(_lcID, _balances[0], _balances[1]);
}
// additive updates of monetary state
// TODO check this for attack vectors
function deposit(
bytes32 _lcID,
address recipient,
uint256 _balance,
bool isToken
) public payable {
require(
Channels[_lcID].isOpen == true,
"Tried adding funds to a closed channel"
);
require(
recipient == Channels[_lcID].partyAddresses[0] ||
recipient == Channels[_lcID].partyAddresses[1]
);
//if(Channels[_lcID].token)
if (Channels[_lcID].partyAddresses[0] == recipient) {
if (isToken) {
require(
Channels[_lcID].token.transferFrom(
msg.sender,
this,
_balance
),
"deposit: token transfer failure"
);
Channels[_lcID].erc20Balances[2] += _balance;
} else {
require(
msg.value == _balance,
"state balance does not match sent value"
);
Channels[_lcID].ethBalances[2] += msg.value;
}
}
if (Channels[_lcID].partyAddresses[1] == recipient) {
if (isToken) {
require(
Channels[_lcID].token.transferFrom(
msg.sender,
this,
_balance
),
"deposit: token transfer failure"
);
Channels[_lcID].erc20Balances[3] += _balance;
} else {
require(
msg.value == _balance,
"state balance does not match sent value"
);
Channels[_lcID].ethBalances[3] += msg.value;
}
}
emit DidLCDeposit(_lcID, recipient, _balance, isToken);
}
// TODO: Check there are no open virtual channels, the client should have cought this before signing a close LC state update
function consensusCloseChannel(
bytes32 _lcID,
uint256 _sequence,
uint256[4] _balances, // 0: ethBalanceA 1:ethBalanceI 2:tokenBalanceA 3:tokenBalanceI
string _sigA,
string _sigI
) public {
// assume num open vc is 0 and root hash is 0x0
//require(Channels[_lcID].sequence < _sequence);
require(Channels[_lcID].isOpen == true);
uint256 totalEthDeposit = Channels[_lcID].initialDeposit[0] +
Channels[_lcID].ethBalances[2] +
Channels[_lcID].ethBalances[3];
uint256 totalTokenDeposit = Channels[_lcID].initialDeposit[1] +
Channels[_lcID].erc20Balances[2] +
Channels[_lcID].erc20Balances[3];
require(totalEthDeposit == _balances[0] + _balances[1]);
require(totalTokenDeposit == _balances[2] + _balances[3]);
bytes32 _state = keccak256(
abi.encodePacked(
_lcID,
true,
_sequence,
uint256(0),
bytes32(0x0),
Channels[_lcID].partyAddresses[0],
Channels[_lcID].partyAddresses[1],
_balances[0],
_balances[1],
_balances[2],
_balances[3]
)
);
require(
Channels[_lcID].partyAddresses[0] == recoverSigner(_state, _sigA)
);
require(
Channels[_lcID].partyAddresses[1] == recoverSigner(_state, _sigI)
);
Channels[_lcID].isOpen = false;
if (_balances[0] != 0 || _balances[1] != 0) {
Channels[_lcID].partyAddresses[0].transfer(_balances[0]);
Channels[_lcID].partyAddresses[1].transfer(_balances[1]);
}
if (_balances[2] != 0 || _balances[3] != 0) {
require(
Channels[_lcID].token.transfer(
Channels[_lcID].partyAddresses[0],
_balances[2]
),
"happyCloseChannel: token transfer failure"
);
require(
Channels[_lcID].token.transfer(
Channels[_lcID].partyAddresses[1],
_balances[3]
),
"happyCloseChannel: token transfer failure"
);
}
numChannels--;
emit DidLCClose(
_lcID,
_sequence,
_balances[0],
_balances[1],
_balances[2],
_balances[3]
);
}
// Byzantine functions
function updateLCstate(
bytes32 _lcID,
uint256[6] updateParams, // [sequence, numOpenVc, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI]
bytes32 _VCroot,
string _sigA,
string _sigI
) public {
Channel storage channel = Channels[_lcID];
require(channel.isOpen);
require(channel.sequence < updateParams[0]); // do same as vc sequence check
require(
channel.ethBalances[0] + channel.ethBalances[1] >=
updateParams[2] + updateParams[3]
);
require(
channel.erc20Balances[0] + channel.erc20Balances[1] >=
updateParams[4] + updateParams[5]
);
if (channel.isUpdateLCSettling == true) {
require(channel.updateLCtimeout > now);
}
bytes32 _state = keccak256(
abi.encodePacked(
_lcID,
false,
updateParams[0],
updateParams[1],
_VCroot,
channel.partyAddresses[0],
channel.partyAddresses[1],
updateParams[2],
updateParams[3],
updateParams[4],
updateParams[5]
)
);
require(channel.partyAddresses[0] == recoverSigner(_state, _sigA));
require(channel.partyAddresses[1] == recoverSigner(_state, _sigI));
// update LC state
channel.sequence = updateParams[0];
channel.numOpenVC = updateParams[1];
channel.ethBalances[0] = updateParams[2];
channel.ethBalances[1] = updateParams[3];
channel.erc20Balances[0] = updateParams[4];
channel.erc20Balances[1] = updateParams[5];
channel.VCrootHash = _VCroot;
channel.isUpdateLCSettling = true;
channel.updateLCtimeout = now + channel.confirmTime;
// make settlement flag
emit DidLCUpdateState(
_lcID,
updateParams[0],
updateParams[1],
updateParams[2],
updateParams[3],
updateParams[4],
updateParams[5],
_VCroot,
channel.updateLCtimeout
);
}
// supply initial state of VC to "prime" the force push game
function initVCstate(
bytes32 _lcID,
bytes32 _vcID,
bytes _proof,
address _partyA,
address _partyB,
uint256[2] _bond,
uint256[4] _balances, // 0: ethBalanceA 1:ethBalanceI 2:tokenBalanceA 3:tokenBalanceI
string sigA
) public {
require(Channels[_lcID].isOpen, "LC is closed.");
// sub-channel must be open
require(!virtualChannels[_vcID].isClose, "VC is closed.");
// Check time has passed on updateLCtimeout and has not passed the time to store a vc state
require(Channels[_lcID].updateLCtimeout < now, "LC timeout not over.");
// prevent rentry of initializing vc state
require(virtualChannels[_vcID].updateVCtimeout == 0);
// partyB is now Ingrid
bytes32 _initState = keccak256(
abi.encodePacked(
_vcID,
uint256(0),
_partyA,
_partyB,
_bond[0],
_bond[1],
_balances[0],
_balances[1],
_balances[2],
_balances[3]
)
);
// Make sure Alice has signed initial vc state (A/B in oldState)
require(_partyA == recoverSigner(_initState, sigA));
// Check the oldState is in the root hash
require(
_isContained(_initState, _proof, Channels[_lcID].VCrootHash) == true
);
virtualChannels[_vcID].partyA = _partyA; // VC participant A
virtualChannels[_vcID].partyB = _partyB; // VC participant B
virtualChannels[_vcID].sequence = uint256(0);
virtualChannels[_vcID].ethBalances[0] = _balances[0];
virtualChannels[_vcID].ethBalances[1] = _balances[1];
virtualChannels[_vcID].erc20Balances[0] = _balances[2];
virtualChannels[_vcID].erc20Balances[1] = _balances[3];
virtualChannels[_vcID].bond = _bond;
virtualChannels[_vcID].updateVCtimeout =
now +
Channels[_lcID].confirmTime;
virtualChannels[_vcID].isInSettlementState = true;
emit DidVCInit(
_lcID,
_vcID,
_proof,
uint256(0),
_partyA,
_partyB,
_balances[0],
_balances[1]
);
}