-
Notifications
You must be signed in to change notification settings - Fork 479
Expand file tree
/
Copy pathlib.rs
More file actions
executable file
·590 lines (514 loc) · 22.1 KB
/
lib.rs
File metadata and controls
executable file
·590 lines (514 loc) · 22.1 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
//! # Payment Channel
//!
//! This implements a payment channel between two parties.
//!
//! ## Warning
//!
//! This contract is an *example*. It is neither audited nor endorsed for production use.
//! Do **not** rely on it to keep anything of value secure.
//!
//! ## Overview
//!
//! Each instantiation of this contract creates a payment channel between a `sender` and a
//! `recipient`. It uses ECDSA signatures to ensure that the `recipient` can only claim
//! the funds if it is signed by the `sender`.
//!
//! ## Error Handling
//!
//! The only panic in the contract is when the signature is invalid. For all other
//! error cases an error is returned. Possible errors are defined in the `Error` enum.
//!
//! ## Interface
//!
//! The interface is modelled after [this blog post](https://programtheblockchain.com/posts/2018/03/02/building-long-lived-payment-channels)
//!
//! ### Deposits
//!
//! The creator of the contract, i.e the `sender`, can deposit funds to the payment
//! channel while creating the payment channel. Any subsequent deposits can be made by
//! transferring funds to the contract's address.
//!
//! ### Withdrawals
//!
//! The `recipient` can `withdraw` from the payment channel anytime by submitting the last
//! `signature` received from the `sender`.
//!
//! The `sender` can only `withdraw` by terminating the payment channel. This is
//! done by calling `start_sender_close` to set an expiration with a subsequent call
//! of `claim_timeout` to claim the funds. This will terminate the payment channel.
#![cfg_attr(not(feature = "std"), no_std, no_main)]
#[ink::contract]
mod payment_channel {
/// Struct for storing the payment channel details.
/// The creator of the contract, i.e the `sender`, can deposit funds to the payment
/// channel while deploying the contract.
#[ink(storage)]
pub struct PaymentChannel {
/// The `AccountId` of the sender of the payment channel.
sender: AccountId,
/// The `AccountId` of the recipient of the payment channel.
recipient: AccountId,
/// The `Timestamp` at which the contract expires. The field is optional.
/// The contract never expires if set to `None`.
expiration: Option<Timestamp>,
/// The `Amount` withdrawn by the recipient.
withdrawn: Balance,
/// The `Timestamp` which will be added to the current time when the sender
/// wishes to close the channel. This will be set at the time of contract
/// instantiation.
close_duration: Timestamp,
}
/// Errors that can occur upon calling this contract.
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(::scale_info::TypeInfo))]
pub enum Error {
/// Returned if caller is not the `sender` while required to.
CallerIsNotSender,
/// Returned if caller is not the `recipient` while required to.
CallerIsNotRecipient,
/// Returned if the requested withdrawal amount is less than the amount
/// that is already already withdrawn.
AmountIsLessThanWithdrawn,
/// Returned if the requested transfer failed. This can be the case if the
/// contract does not have sufficient free funds or if the transfer would
/// have brought the contract's balance below minimum balance.
TransferFailed,
/// Returned if the contract hasn't expired yet and the `sender` wishes to
/// close the channel.
NotYetExpired,
/// Returned if the signature is invalid.
InvalidSignature,
}
/// Type alias for the contract's `Result` type.
pub type Result<T> = core::result::Result<T, Error>;
/// Emitted when the sender starts closing the channel.
#[ink(event)]
pub struct SenderCloseStarted {
expiration: Timestamp,
close_duration: Timestamp,
}
impl PaymentChannel {
/// The only constructor of the contract.
///
/// The arguments `recipient` and `close_duration` are required.
///
/// `expiration` will be set to `None`, so that the contract will
/// never expire. `sender` can call `start_sender_close` to override
/// this. `sender` will be able to claim the remaining balance by calling
/// `claim_timeout` after `expiration` has passed.
#[ink(constructor)]
pub fn new(recipient: AccountId, close_duration: Timestamp) -> Self {
Self {
sender: Self::env().caller(),
recipient,
expiration: None,
withdrawn: 0,
close_duration,
}
}
/// The `recipient` can close the payment channel anytime. The specified
/// `amount` will be sent to the `recipient` and the remainder will go
/// back to the `sender`.
#[ink(message)]
pub fn close(&mut self, amount: Balance, signature: [u8; 65]) -> Result<()> {
self.close_inner(amount, signature)?;
self.env().terminate_contract(self.sender);
}
/// We split this out in order to make testing `close` simpler.
fn close_inner(&mut self, amount: Balance, signature: [u8; 65]) -> Result<()> {
if self.env().caller() != self.recipient {
return Err(Error::CallerIsNotRecipient)
}
if amount < self.withdrawn {
return Err(Error::AmountIsLessThanWithdrawn)
}
// Signature validation
if !self.is_signature_valid(amount, signature) {
return Err(Error::InvalidSignature)
}
// We checked that amount >= self.withdrawn
#[allow(clippy::arithmetic_side_effects)]
self.env()
.transfer(self.recipient, amount - self.withdrawn)
.map_err(|_| Error::TransferFailed)?;
Ok(())
}
/// If the `sender` wishes to close the channel and withdraw the funds they can
/// do so by setting the `expiration`. If the `expiration` is reached, the
/// sender will be able to call `claim_timeout` to claim the remaining funds
/// and the channel will be terminated. This emits an event that the recipient can
/// listen to in order to withdraw the funds before the `expiration`.
#[ink(message)]
pub fn start_sender_close(&mut self) -> Result<()> {
if self.env().caller() != self.sender {
return Err(Error::CallerIsNotSender)
}
let now = self.env().block_timestamp();
let expiration = now.checked_add(self.close_duration).unwrap();
self.env().emit_event(SenderCloseStarted {
expiration,
close_duration: self.close_duration,
});
self.expiration = Some(expiration);
Ok(())
}
/// If the timeout is reached (`current_time >= expiration`) without the
/// recipient closing the channel, then the remaining balance is released
/// back to the `sender`.
#[ink(message)]
pub fn claim_timeout(&mut self) -> Result<()> {
match self.expiration {
Some(expiration) => {
// expiration is set. Check if it's reached and if so, release the
// funds and terminate the contract.
let now = self.env().block_timestamp();
if now < expiration {
return Err(Error::NotYetExpired)
}
self.env().terminate_contract(self.sender);
}
None => Err(Error::NotYetExpired),
}
}
/// The `recipient` can withdraw the funds from the channel at any time.
#[ink(message)]
pub fn withdraw(&mut self, amount: Balance, signature: [u8; 65]) -> Result<()> {
if self.env().caller() != self.recipient {
return Err(Error::CallerIsNotRecipient)
}
// Signature validation
if !self.is_signature_valid(amount, signature) {
return Err(Error::InvalidSignature)
}
// Make sure there's something to withdraw (guards against underflow)
if amount < self.withdrawn {
return Err(Error::AmountIsLessThanWithdrawn)
}
// We checked that amount >= self.withdrawn
#[allow(clippy::arithmetic_side_effects)]
let amount_to_withdraw = amount - self.withdrawn;
self.withdrawn.checked_add(amount_to_withdraw).unwrap();
self.env()
.transfer(self.recipient, amount_to_withdraw)
.map_err(|_| Error::TransferFailed)?;
Ok(())
}
/// Returns the `sender` of the contract.
#[ink(message)]
pub fn get_sender(&self) -> AccountId {
self.sender
}
/// Returns the `recipient` of the contract.
#[ink(message)]
pub fn get_recipient(&self) -> AccountId {
self.recipient
}
/// Returns the `expiration` of the contract.
#[ink(message)]
pub fn get_expiration(&self) -> Option<Timestamp> {
self.expiration
}
/// Returns the `withdrawn` amount of the contract.
#[ink(message)]
pub fn get_withdrawn(&self) -> Balance {
self.withdrawn
}
/// Returns the `close_duration` of the contract.
#[ink(message)]
pub fn get_close_duration(&self) -> Timestamp {
self.close_duration
}
/// Returns the `balance` of the contract.
#[ink(message)]
pub fn get_balance(&self) -> Balance {
self.env().balance()
}
}
#[ink(impl)]
impl PaymentChannel {
fn is_signature_valid(&self, amount: Balance, signature: [u8; 65]) -> bool {
let encodable = (self.env().account_id(), amount);
let mut message =
<ink::env::hash::Sha2x256 as ink::env::hash::HashOutput>::Type::default();
ink::env::hash_encoded::<ink::env::hash::Sha2x256, _>(
&encodable,
&mut message,
);
let mut pub_key = [0; 33];
ink::env::ecdsa_recover(&signature, &message, &mut pub_key)
.unwrap_or_else(|err| panic!("recover failed: {err:?}"));
let mut signature_account_id = [0; 32];
<ink::env::hash::Blake2x256 as ink::env::hash::CryptoHash>::hash(
&pub_key,
&mut signature_account_id,
);
self.recipient == signature_account_id.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use hex_literal;
use sp_core::{
Encode,
Pair,
};
fn default_accounts(
) -> ink::env::test::DefaultAccounts<ink::env::DefaultEnvironment> {
ink::env::test::default_accounts::<ink::env::DefaultEnvironment>()
}
fn set_next_caller(caller: AccountId) {
ink::env::test::set_caller::<ink::env::DefaultEnvironment>(caller);
}
fn set_account_balance(account: AccountId, balance: Balance) {
ink::env::test::set_account_balance::<ink::env::DefaultEnvironment>(
account, balance,
);
}
fn get_account_balance(account: AccountId) -> Balance {
ink::env::test::get_account_balance::<ink::env::DefaultEnvironment>(account)
.expect("Cannot get account balance")
}
fn advance_block() {
ink::env::test::advance_block::<ink::env::DefaultEnvironment>();
}
fn get_current_time() -> Timestamp {
let since_the_epoch = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("Time went backwards");
since_the_epoch.as_secs()
+ since_the_epoch.subsec_nanos() as u64 / 1_000_000_000
}
fn get_dan() -> AccountId {
// Use Dan's seed
// `subkey inspect //Dan --scheme Ecdsa --output-type json | jq .secretSeed`
let seed = hex_literal::hex!(
"c31fa562972de437802e0df146b16146349590b444db41f7e3eb9deedeee6f64"
);
let pair = sp_core::ecdsa::Pair::from_seed(&seed);
let pub_key = pair.public();
let compressed_pub_key: [u8; 33] = pub_key.encode()[..]
.try_into()
.expect("slice with incorrect length");
let mut account_id = [0; 32];
<ink::env::hash::Blake2x256 as ink::env::hash::CryptoHash>::hash(
&compressed_pub_key,
&mut account_id,
);
account_id.into()
}
fn contract_id() -> AccountId {
let accounts = default_accounts();
let contract_id = accounts.charlie;
ink::env::test::set_callee::<ink::env::DefaultEnvironment>(contract_id);
contract_id
}
fn sign(contract_id: AccountId, amount: Balance) -> [u8; 65] {
let encodable = (contract_id, amount);
let mut hash =
<ink::env::hash::Sha2x256 as ink::env::hash::HashOutput>::Type::default(); // 256-bit buffer
ink::env::hash_encoded::<ink::env::hash::Sha2x256, _>(&encodable, &mut hash);
// Use Dan's seed
// `subkey inspect //Dan --scheme Ecdsa --output-type json | jq .secretSeed`
let seed = hex_literal::hex!(
"c31fa562972de437802e0df146b16146349590b444db41f7e3eb9deedeee6f64"
);
let pair = sp_core::ecdsa::Pair::from_seed(&seed);
let signature = pair.sign_prehashed(&hash);
signature.0
}
#[ink::test]
fn test_deposit() {
// given
let accounts = default_accounts();
let initial_balance = 10_000;
let close_duration = 360_000;
let mock_deposit_value = 1_000;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(accounts.bob, initial_balance);
// when
// Push the new execution context with Alice as the caller and
// the `mock_deposit_value` as the value deposited.
// Note: Currently there is no way to transfer funds to the contract.
set_next_caller(accounts.alice);
let payment_channel = PaymentChannel::new(accounts.bob, close_duration);
let contract_id = contract_id();
set_account_balance(contract_id, mock_deposit_value);
// then
assert_eq!(payment_channel.get_balance(), mock_deposit_value);
}
#[ink::test]
fn test_close() {
// given
let accounts = default_accounts();
let dan = get_dan();
let close_duration = 360_000;
let mock_deposit_value = 1_000;
let amount = 500;
let initial_balance = 10_000;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(dan, initial_balance);
// when
set_next_caller(accounts.alice);
let mut payment_channel = PaymentChannel::new(dan, close_duration);
let contract_id = contract_id();
set_account_balance(contract_id, mock_deposit_value);
set_next_caller(dan);
let signature = sign(contract_id, amount);
// then
let should_close = move || payment_channel.close(amount, signature).unwrap();
ink::env::test::assert_contract_termination::<ink::env::DefaultEnvironment, _>(
should_close,
accounts.alice,
amount,
);
assert_eq!(get_account_balance(dan), initial_balance + amount);
}
#[ink::test]
fn close_fails_invalid_signature() {
// given
let accounts = default_accounts();
let dan = get_dan();
let mock_deposit_value = 1_000;
let close_duration = 360_000;
let amount = 400;
let unexpected_amount = amount + 1;
let initial_balance = 10_000;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(dan, initial_balance);
// when
set_next_caller(accounts.alice);
let mut payment_channel = PaymentChannel::new(dan, close_duration);
let contract_id = contract_id();
set_account_balance(contract_id, mock_deposit_value);
set_next_caller(dan);
let signature = sign(contract_id, amount);
// then
let res = payment_channel.close_inner(unexpected_amount, signature);
assert!(res.is_err(), "Expected an error, got {res:?} instead.");
assert_eq!(res.unwrap_err(), Error::InvalidSignature,);
}
#[ink::test]
fn test_withdraw() {
// given
let accounts = default_accounts();
let dan = get_dan();
let initial_balance = 10_000;
let mock_deposit_value = 1_000;
let close_duration = 360_000;
let amount = 500;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(dan, initial_balance);
// when
set_next_caller(accounts.alice);
let mut payment_channel = PaymentChannel::new(dan, close_duration);
let contract_id = contract_id();
set_account_balance(contract_id, mock_deposit_value);
set_next_caller(dan);
let signature = sign(contract_id, amount);
payment_channel
.withdraw(amount, signature)
.expect("withdraw failed");
// then
assert_eq!(payment_channel.get_balance(), amount);
assert_eq!(get_account_balance(dan), initial_balance + amount);
}
#[ink::test]
fn withdraw_fails_invalid_signature() {
// given
let accounts = default_accounts();
let dan = get_dan();
let initial_balance = 10_000;
let close_duration = 360_000;
let amount = 400;
let unexpected_amount = amount + 1;
let mock_deposit_value = 1_000;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(dan, initial_balance);
// when
set_next_caller(accounts.alice);
let mut payment_channel = PaymentChannel::new(dan, close_duration);
let contract_id = contract_id();
set_account_balance(contract_id, mock_deposit_value);
set_next_caller(dan);
let signature = sign(contract_id, amount);
// then
let res = payment_channel.withdraw(unexpected_amount, signature);
assert!(res.is_err(), "Expected an error, got {res:?} instead.");
assert_eq!(res.unwrap_err(), Error::InvalidSignature,);
}
#[ink::test]
fn test_start_sender_close() {
// given
let accounts = default_accounts();
let initial_balance = 10_000;
let mock_deposit_value = 1_000;
let close_duration = 1;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(accounts.bob, initial_balance);
// when
set_next_caller(accounts.alice);
let mut payment_channel = PaymentChannel::new(accounts.bob, close_duration);
let contract_id = contract_id();
set_account_balance(contract_id, mock_deposit_value);
payment_channel
.start_sender_close()
.expect("start_sender_close failed");
advance_block();
// then
let now = get_current_time();
assert!(now > payment_channel.get_expiration().unwrap());
}
#[ink::test]
fn test_claim_timeout() {
// given
let accounts = default_accounts();
let initial_balance = 10_000;
let close_duration = 1;
let mock_deposit_value = 1_000;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(accounts.bob, initial_balance);
// when
set_next_caller(accounts.alice);
let contract_id = contract_id();
let mut payment_channel = PaymentChannel::new(accounts.bob, close_duration);
set_account_balance(contract_id, mock_deposit_value);
payment_channel
.start_sender_close()
.expect("start_sender_close failed");
advance_block();
// then
let should_close = move || payment_channel.claim_timeout().unwrap();
ink::env::test::assert_contract_termination::<ink::env::DefaultEnvironment, _>(
should_close,
accounts.alice,
mock_deposit_value,
);
assert_eq!(
get_account_balance(accounts.alice),
initial_balance + mock_deposit_value
);
}
#[ink::test]
fn test_getters() {
// given
let accounts = default_accounts();
let initial_balance = 10_000;
let mock_deposit_value = 1_000;
let close_duration = 360_000;
set_account_balance(accounts.alice, initial_balance);
set_account_balance(accounts.bob, initial_balance);
// when
set_next_caller(accounts.alice);
let contract_id = contract_id();
let payment_channel = PaymentChannel::new(accounts.bob, close_duration);
set_account_balance(contract_id, mock_deposit_value);
// then
assert_eq!(payment_channel.get_sender(), accounts.alice);
assert_eq!(payment_channel.get_recipient(), accounts.bob);
assert_eq!(payment_channel.get_balance(), mock_deposit_value);
assert_eq!(payment_channel.get_close_duration(), close_duration);
assert_eq!(payment_channel.get_withdrawn(), 0);
}
}
}