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
use std::sync::Arc;

use raiden_primitives::{
	packing::{
		pack_balance_proof,
		pack_balance_proof_message,
	},
	signing::recover,
	types::{
		Address,
		BalanceHash,
		BlockHash,
		BlockId,
		CanonicalIdentifier,
		ChainID,
		ChannelIdentifier,
		GasLimit,
		GasPrice,
		MessageTypeId,
		Nonce,
		Signature,
		TransactionHash,
		H256,
		U256,
	},
};
use raiden_state_machine::types::ChannelStatus;
use web3::{
	contract::Options,
	types::BlockNumber,
	Transport,
	Web3,
};

use crate::{
	contracts::GasMetadata,
	proxies::{
		Account,
		ChannelData,
		ParticipantDetails,
		ProxyError,
		TokenNetworkProxy,
	},
	transactions::Transaction,
};

/// On-chain data to validate updating a channel's transfer.
#[derive(Clone)]
pub struct ChannelUpdateTransferTransactionData {
	chain_id: ChainID,
	channel_onchain_details: ChannelData,
	closer_details: ParticipantDetails,
}

/// Parameters required to update channel's transfer.
#[derive(Clone)]
pub struct ChannelUpdateTransferTransactionParams {
	pub(crate) channel_identifier: ChannelIdentifier,
	pub(crate) nonce: Nonce,
	pub(crate) partner: Address,
	pub(crate) balance_hash: BalanceHash,
	pub(crate) additional_hash: H256,
	pub(crate) closing_signature: Signature,
	pub(crate) non_closing_signature: Signature,
}

/// Channel update transfer transaction type.
pub struct ChannelUpdateTransferTransaction<T: Transport> {
	pub(crate) web3: Web3<T>,
	pub(crate) account: Account<T>,
	pub(crate) token_network: TokenNetworkProxy<T>,
	pub(crate) gas_metadata: Arc<GasMetadata>,
}

#[async_trait::async_trait]
impl<T> Transaction for ChannelUpdateTransferTransaction<T>
where
	T: Transport + Send + Sync,
	T::Out: Send,
{
	type Output = TransactionHash;
	type Params = ChannelUpdateTransferTransactionParams;
	type Data = ChannelUpdateTransferTransactionData;

	async fn onchain_data(
		&self,
		params: Self::Params,
		at_block_hash: BlockHash,
	) -> Result<Self::Data, ProxyError> {
		let channel_onchain_details = self
			.token_network
			.channel_details(
				Some(params.channel_identifier),
				self.account.address(),
				params.partner,
				at_block_hash,
			)
			.await?;

		let closer_details = self
			.token_network
			.participant_details(
				params.channel_identifier,
				params.partner,
				self.account.address(),
				Some(at_block_hash),
			)
			.await?;

		let chain_id = self.token_network.chain_id(at_block_hash).await?;

		Ok(ChannelUpdateTransferTransactionData {
			channel_onchain_details,
			chain_id,
			closer_details,
		})
	}

	async fn validate_preconditions(
		&self,
		params: Self::Params,
		data: Self::Data,
		_block: BlockHash,
	) -> Result<(), ProxyError> {
		let canonical_identifier = CanonicalIdentifier {
			chain_identifier: data.chain_id,
			token_network_address: self.token_network.contract.address(),
			channel_identifier: params.channel_identifier,
		};

		let partner_signed_data = pack_balance_proof(
			params.nonce,
			params.balance_hash,
			params.additional_hash,
			canonical_identifier.clone(),
			MessageTypeId::BalanceProof,
		);

		let our_signed_data = pack_balance_proof_message(
			params.nonce,
			params.balance_hash,
			params.additional_hash,
			canonical_identifier.clone(),
			MessageTypeId::BalanceProofUpdate,
			params.closing_signature.clone(),
		);

		let partner_recovered_address =
			recover(&partner_signed_data.0, &params.closing_signature.0).map_err(|_| {
				ProxyError::Unrecoverable("Could not verify the closing signature".to_owned())
			})?;

		let our_recovered_address = recover(&our_signed_data.0, &params.non_closing_signature.0)
			.map_err(|_| {
				ProxyError::Unrecoverable("Could not verify the non-closing signature".to_owned())
			})?;

		if partner_recovered_address != params.partner {
			return Err(ProxyError::Unrecoverable("Invalid closing signature".to_owned()))
		}
		if our_recovered_address != self.account.address() {
			return Err(ProxyError::Unrecoverable("Invalid non-closing signature".to_owned()))
		}

		if data.channel_onchain_details.status != ChannelStatus::Closed {
			return Err(ProxyError::Recoverable(format!(
				"The channel was not closed at the provided block"
			)))
		}

		let current_block_number: U256 =
			self.web3.eth().block_number().await.map_err(ProxyError::Web3)?.as_u64().into();

		if data.channel_onchain_details.settle_block_number < current_block_number {
			return Err(ProxyError::BrokenPrecondition(format!(
				"Update transfer cannot be called after settlement period. \
                 This call should never have been attempted"
			)))
		}

		if data.closer_details.nonce == params.nonce {
			return Err(ProxyError::BrokenPrecondition(format!(
				"Update transfer was already done. \
                 This call should never have been attempted"
			)))
		}

		Ok(())
	}

	async fn submit(
		&self,
		params: Self::Params,
		_data: Self::Data,
		gas_estimate: GasLimit,
		gas_price: GasPrice,
	) -> Result<Self::Output, ProxyError> {
		let nonce = self.account.peek_next_nonce().await;
		self.account.next_nonce().await;

		let receipt = self
			.token_network
			.contract
			.signed_call_with_confirmations(
				"updateNonClosingBalanceProof",
				(
					params.channel_identifier,
					params.partner,
					self.account.address(),
					params.balance_hash,
					params.nonce,
					params.additional_hash,
					params.closing_signature,
					params.non_closing_signature,
				),
				Options::with(|opt| {
					opt.value = Some(GasLimit::from(0));
					opt.gas = Some(gas_estimate);
					opt.nonce = Some(nonce);
					opt.gas_price = Some(gas_price);
				}),
				1,
				self.account.private_key(),
			)
			.await?;

		Ok(receipt.transaction_hash)
	}

	async fn validate_postconditions(
		&self,
		params: Self::Params,
		_block: BlockHash,
	) -> Result<Self::Output, ProxyError> {
		let failed_at = self
			.web3
			.eth()
			.block(BlockId::Number(BlockNumber::Latest))
			.await
			.map_err(ProxyError::Web3)?
			.ok_or(ProxyError::Recoverable("Block not found".to_string()))?;

		let failed_at_blocknumber = failed_at.number.unwrap();
		let failed_at_blockhash = failed_at.hash.unwrap();

		self.account
			.check_for_insufficient_eth(
				self.gas_metadata.get("TokenNetwork.updateNonClosingBalanceProof").into(),
				failed_at_blocknumber,
			)
			.await?;

		let data = self.onchain_data(params.clone(), failed_at_blockhash).await?;

		if data.channel_onchain_details.channel_identifier == ChannelIdentifier::zero() ||
			data.channel_onchain_details.channel_identifier > params.channel_identifier
		{
			return Err(ProxyError::Recoverable(
				"The provided channel identifier does not match the value on-chain \
                 at the block the update transfer was mined."
					.to_owned(),
			))
		}
		if data.channel_onchain_details.status == ChannelStatus::Settled ||
			data.channel_onchain_details.status == ChannelStatus::Removed
		{
			return Err(ProxyError::Recoverable(
				"Cannot call settle on a channel that has been settled already".to_owned(),
			))
		}

		if data.channel_onchain_details.settle_block_number < failed_at_blocknumber.as_u64().into()
		{
			return Err(ProxyError::Recoverable(
				"Update transfer transaction sent after settlement window".to_owned(),
			))
		}

		if data.closer_details.nonce != params.nonce {
			return Err(ProxyError::Recoverable(
				"Update transfer failed. The on-chain nonce is higher than our expected."
					.to_owned(),
			))
		}

		if data.channel_onchain_details.status == ChannelStatus::Closed ||
			data.channel_onchain_details.status == ChannelStatus::Closing ||
			data.channel_onchain_details.status == ChannelStatus::Opened
		{
			return Err(ProxyError::Recoverable("The channel state changed unexpectedly".to_owned()))
		}

		Err(ProxyError::Recoverable(format!(
			"UpdateTransfer channel failed. Gas estimation failed for
            unknown reason. Reference block {} - {}",
			failed_at_blockhash, failed_at_blocknumber,
		)))
	}

	async fn estimate_gas(
		&self,
		params: Self::Params,
		_data: Self::Data,
	) -> Result<(GasLimit, GasPrice), ProxyError> {
		let nonce = self.account.peek_next_nonce().await;
		let gas_price = self.web3.eth().gas_price().await.map_err(ProxyError::Web3)?;

		self.token_network
			.contract
			.estimate_gas(
				"updateNonClosingBalanceProof",
				(
					params.channel_identifier,
					params.partner,
					self.account.address(),
					params.balance_hash,
					params.nonce,
					params.additional_hash,
					params.closing_signature,
					params.non_closing_signature,
				),
				self.account.address(),
				Options::with(|opt| {
					opt.value = Some(GasLimit::from(0));
					opt.nonce = Some(nonce);
					opt.gas_price = Some(gas_price);
				}),
			)
			.await
			.map(|estimate| (estimate, gas_price))
			.map_err(ProxyError::ChainError)
	}
}