@keep-network/tbtc-v2 0.1.0 → 0.1.1-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/.chainId +1 -1
  3. package/artifacts/Bank.json +807 -0
  4. package/artifacts/Bridge.json +2300 -0
  5. package/artifacts/Deposit.json +117 -0
  6. package/artifacts/DepositSweep.json +77 -0
  7. package/artifacts/EcdsaDkgValidator.json +532 -0
  8. package/artifacts/EcdsaInactivity.json +156 -0
  9. package/artifacts/EcdsaSortitionPool.json +1004 -0
  10. package/artifacts/Fraud.json +164 -0
  11. package/artifacts/KeepRegistry.json +99 -0
  12. package/artifacts/KeepStake.json +286 -0
  13. package/artifacts/KeepToken.json +711 -0
  14. package/artifacts/KeepTokenStaking.json +483 -0
  15. package/artifacts/MovingFunds.json +249 -0
  16. package/artifacts/NuCypherStakingEscrow.json +256 -0
  17. package/artifacts/NuCypherToken.json +711 -0
  18. package/artifacts/RandomBeaconStub.json +141 -0
  19. package/artifacts/Redemption.json +174 -0
  20. package/artifacts/ReimbursementPool.json +509 -0
  21. package/artifacts/Relay.json +123 -0
  22. package/artifacts/T.json +1148 -0
  23. package/artifacts/TBTC.json +36 -35
  24. package/artifacts/TBTCToken.json +738 -0
  25. package/artifacts/TBTCVault.json +691 -0
  26. package/artifacts/TokenStaking.json +2288 -0
  27. package/artifacts/TokenholderGovernor.json +1795 -0
  28. package/artifacts/TokenholderTimelock.json +1058 -0
  29. package/artifacts/VendingMachine.json +34 -33
  30. package/artifacts/VendingMachineKeep.json +400 -0
  31. package/artifacts/VendingMachineNuCypher.json +400 -0
  32. package/artifacts/WalletRegistry.json +1843 -0
  33. package/artifacts/WalletRegistryGovernance.json +2754 -0
  34. package/artifacts/Wallets.json +186 -0
  35. package/artifacts/solcInputs/5e62cff1ead0900b07facca4b559e818.json +314 -0
  36. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  37. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  38. package/build/contracts/bank/Bank.sol/Bank.dbg.json +4 -0
  39. package/build/contracts/bank/Bank.sol/Bank.json +542 -0
  40. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.dbg.json +4 -0
  41. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.json +34 -0
  42. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  43. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +10 -0
  44. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +4 -0
  45. package/build/contracts/bridge/Bridge.sol/Bridge.json +2686 -0
  46. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  47. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +226 -0
  48. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  49. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  50. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +4 -0
  51. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +30 -0
  52. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  53. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  54. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +4 -0
  55. package/build/contracts/bridge/Fraud.sol/Fraud.json +86 -0
  56. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +4 -0
  57. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.json +10 -0
  58. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  59. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  60. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  61. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +138 -0
  62. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +4 -0
  63. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +10 -0
  64. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +4 -0
  65. package/build/contracts/bridge/Redemption.sol/Redemption.json +92 -0
  66. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  67. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  68. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  69. package/build/contracts/bridge/Wallets.sol/Wallets.json +112 -0
  70. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  71. package/build/contracts/token/TBTC.sol/TBTC.json +4 -4
  72. package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +4 -0
  73. package/build/contracts/vault/DonationVault.sol/DonationVault.json +108 -0
  74. package/build/contracts/vault/IVault.sol/IVault.dbg.json +4 -0
  75. package/build/contracts/vault/IVault.sol/IVault.json +52 -0
  76. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +4 -0
  77. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +449 -0
  78. package/contracts/GovernanceUtils.sol +4 -4
  79. package/contracts/bank/Bank.sol +436 -0
  80. package/contracts/bank/IReceiveBalanceApproval.sol +45 -0
  81. package/contracts/bridge/BitcoinTx.sol +326 -0
  82. package/contracts/bridge/Bridge.sol +1793 -0
  83. package/contracts/bridge/BridgeState.sol +739 -0
  84. package/contracts/bridge/Deposit.sol +269 -0
  85. package/contracts/bridge/DepositSweep.sol +574 -0
  86. package/contracts/bridge/EcdsaLib.sol +45 -0
  87. package/contracts/bridge/Fraud.sol +579 -0
  88. package/contracts/bridge/Heartbeat.sol +112 -0
  89. package/contracts/bridge/IRelay.sol +28 -0
  90. package/contracts/bridge/MovingFunds.sol +1077 -0
  91. package/contracts/bridge/Redemption.sol +1020 -0
  92. package/contracts/bridge/VendingMachine.sol +2 -2
  93. package/contracts/bridge/Wallets.sol +719 -0
  94. package/contracts/hardhat-dependency-compiler/.hardhat-dependency-compiler +1 -0
  95. package/contracts/hardhat-dependency-compiler/@keep-network/ecdsa/contracts/WalletRegistry.sol +3 -0
  96. package/contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol +3 -0
  97. package/contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol +3 -0
  98. package/contracts/token/TBTC.sol +1 -1
  99. package/contracts/vault/DonationVault.sol +125 -0
  100. package/contracts/vault/IVault.sol +44 -0
  101. package/contracts/vault/TBTCVault.sol +305 -0
  102. package/deploy/00_resolve_relay.ts +28 -0
  103. package/deploy/00_resolve_tbtc_v1_token.ts +1 -1
  104. package/deploy/01_deploy_tbtc_v2_token.ts +8 -1
  105. package/deploy/02_deploy_vending_machine.ts +7 -0
  106. package/deploy/{03_transfer_roles.ts → 03_transfer_vending_machine_roles.ts} +1 -1
  107. package/deploy/04_deploy_bank.ts +27 -0
  108. package/deploy/05_deploy_bridge.ts +80 -0
  109. package/deploy/06_deploy_tbtc_vault.ts +30 -0
  110. package/deploy/07_bank_update_bridge.ts +19 -0
  111. package/deploy/08_transfer_bank_ownership.ts +15 -0
  112. package/deploy/09_transfer_tbtc_vault_ownership.ts +15 -0
  113. package/deploy/10_transfer_bridge_governance.ts +20 -0
  114. package/deploy/11_initialize_wallet_owner.ts +18 -0
  115. package/deploy/11_transfer_proxy_admin_ownership.ts +30 -0
  116. package/deploy/12_deploy_proxy_admin_with_deputy.ts +33 -0
  117. package/export/deploy/00_resolve_relay.js +24 -0
  118. package/export/deploy/00_resolve_tbtc_v1_token.js +24 -0
  119. package/export/deploy/01_deploy_tbtc_v2_token.js +19 -0
  120. package/export/deploy/02_deploy_vending_machine.js +25 -0
  121. package/export/deploy/03_transfer_vending_machine_roles.js +19 -0
  122. package/export/deploy/04_deploy_bank.js +21 -0
  123. package/export/deploy/05_deploy_bridge.js +69 -0
  124. package/export/deploy/06_deploy_tbtc_vault.js +24 -0
  125. package/export/deploy/07_bank_update_bridge.js +13 -0
  126. package/export/deploy/08_transfer_bank_ownership.js +11 -0
  127. package/export/deploy/09_transfer_tbtc_vault_ownership.js +11 -0
  128. package/export/deploy/10_transfer_bridge_governance.js +11 -0
  129. package/export/deploy/11_initialize_wallet_owner.js +14 -0
  130. package/export/deploy/11_transfer_proxy_admin_ownership.js +23 -0
  131. package/export/deploy/12_deploy_proxy_admin_with_deputy.js +22 -0
  132. package/export/hardhat.config.js +169 -0
  133. package/export/test/bank/Bank.test.js +1012 -0
  134. package/export/test/bridge/Bridge.Deployment.test.js +76 -0
  135. package/export/test/bridge/Bridge.Deposit.test.js +1834 -0
  136. package/export/test/bridge/Bridge.Frauds.test.js +1349 -0
  137. package/export/test/bridge/Bridge.MovingFunds.test.js +2437 -0
  138. package/export/test/bridge/Bridge.Parameters.test.js +400 -0
  139. package/export/test/bridge/Bridge.Redemption.test.js +2523 -0
  140. package/export/test/bridge/Bridge.Vaults.test.js +74 -0
  141. package/export/test/bridge/Bridge.Wallets.test.js +1017 -0
  142. package/export/test/bridge/EcdsaLib.test.js +46 -0
  143. package/export/test/bridge/Heartbeat.test.js +77 -0
  144. package/export/test/bridge/VendingMachine.Upgrade.test.js +160 -0
  145. package/export/test/bridge/VendingMachine.test.js +762 -0
  146. package/export/test/data/deposit-sweep.js +655 -0
  147. package/export/test/data/ecdsa.js +18 -0
  148. package/export/test/data/fraud.js +158 -0
  149. package/export/test/data/moving-funds.js +815 -0
  150. package/export/test/data/redemption.js +1011 -0
  151. package/export/test/fixtures/bridge.js +54 -0
  152. package/export/test/fixtures/index.js +57 -0
  153. package/export/test/helpers/contract-test-helpers.js +18 -0
  154. package/export/test/integration/Slashing.test.js +279 -0
  155. package/export/test/integration/WalleCreation.test.js +66 -0
  156. package/export/test/integration/utils/ecdsa-wallet-registry.js +137 -0
  157. package/export/test/integration/utils/fixture.js +77 -0
  158. package/export/test/integration/utils/gas.js +36 -0
  159. package/export/test/integration/utils/random-beacon.js +26 -0
  160. package/export/test/integration/utils/staking.js +19 -0
  161. package/export/test/vault/DonationVault.test.js +202 -0
  162. package/export/test/vault/TBTCVault.Redemption.test.js +357 -0
  163. package/export/test/vault/TBTCVault.test.js +768 -0
  164. package/export/typechain/BTCUtils.js +2 -0
  165. package/export/typechain/Bank.js +2 -0
  166. package/export/typechain/BankStub.js +2 -0
  167. package/export/typechain/Bridge.js +2 -0
  168. package/export/typechain/BridgeState.js +2 -0
  169. package/export/typechain/BridgeStub.js +2 -0
  170. package/export/typechain/Deposit.js +2 -0
  171. package/export/typechain/DepositSweep.js +2 -0
  172. package/export/typechain/DonationVault.js +2 -0
  173. package/export/typechain/ERC165.js +2 -0
  174. package/export/typechain/ERC1967Proxy.js +2 -0
  175. package/export/typechain/ERC1967Upgrade.js +2 -0
  176. package/export/typechain/ERC20WithPermit.js +2 -0
  177. package/export/typechain/ERC721.js +2 -0
  178. package/export/typechain/EcdsaAuthorization.js +2 -0
  179. package/export/typechain/EcdsaDkg.js +2 -0
  180. package/export/typechain/EcdsaDkgValidator.js +2 -0
  181. package/export/typechain/EcdsaInactivity.js +2 -0
  182. package/export/typechain/Fraud.js +2 -0
  183. package/export/typechain/Governable.js +2 -0
  184. package/export/typechain/HeartbeatStub.js +2 -0
  185. package/export/typechain/IApplication.js +2 -0
  186. package/export/typechain/IApproveAndCall.js +2 -0
  187. package/export/typechain/IBeacon.js +2 -0
  188. package/export/typechain/IERC165.js +2 -0
  189. package/export/typechain/IERC1822Proxiable.js +2 -0
  190. package/export/typechain/IERC20.js +2 -0
  191. package/export/typechain/IERC20Metadata.js +2 -0
  192. package/export/typechain/IERC20WithPermit.js +2 -0
  193. package/export/typechain/IERC721.js +2 -0
  194. package/export/typechain/IERC721Metadata.js +2 -0
  195. package/export/typechain/IERC721Receiver.js +2 -0
  196. package/export/typechain/IRandomBeacon.js +2 -0
  197. package/export/typechain/IRandomBeaconConsumer.js +2 -0
  198. package/export/typechain/IReceiveApproval.js +2 -0
  199. package/export/typechain/IReceiveBalanceApproval.js +2 -0
  200. package/export/typechain/IRelay.js +2 -0
  201. package/export/typechain/IStaking.js +2 -0
  202. package/export/typechain/IVault.js +2 -0
  203. package/export/typechain/IWalletOwner.js +2 -0
  204. package/export/typechain/IWalletRegistry.js +2 -0
  205. package/export/typechain/Initializable.js +2 -0
  206. package/export/typechain/MisfundRecovery.js +2 -0
  207. package/export/typechain/MovingFunds.js +2 -0
  208. package/export/typechain/Ownable.js +2 -0
  209. package/export/typechain/Proxy.js +2 -0
  210. package/export/typechain/ProxyAdmin.js +2 -0
  211. package/export/typechain/ReceiveApprovalStub.js +2 -0
  212. package/export/typechain/Redemption.js +2 -0
  213. package/export/typechain/Reimbursable.js +2 -0
  214. package/export/typechain/ReimbursementPool.js +2 -0
  215. package/export/typechain/Rewards.js +2 -0
  216. package/export/typechain/SortitionPool.js +2 -0
  217. package/export/typechain/SortitionTree.js +2 -0
  218. package/export/typechain/TBTC.js +2 -0
  219. package/export/typechain/TBTCVault.js +2 -0
  220. package/export/typechain/TestERC20.js +2 -0
  221. package/export/typechain/TestERC721.js +2 -0
  222. package/export/typechain/TestEcdsaLib.js +2 -0
  223. package/export/typechain/TestRelay.js +2 -0
  224. package/export/typechain/TransparentUpgradeableProxy.js +2 -0
  225. package/export/typechain/VendingMachine.js +2 -0
  226. package/export/typechain/WalletRegistry.js +2 -0
  227. package/export/typechain/Wallets.js +2 -0
  228. package/export/typechain/common.js +2 -0
  229. package/export/typechain/factories/BTCUtils__factory.js +94 -0
  230. package/export/typechain/factories/BankStub__factory.js +586 -0
  231. package/export/typechain/factories/Bank__factory.js +573 -0
  232. package/export/typechain/factories/BridgeState__factory.js +257 -0
  233. package/export/typechain/factories/BridgeStub__factory.js +2912 -0
  234. package/export/typechain/factories/Bridge__factory.js +2526 -0
  235. package/export/typechain/factories/DepositSweep__factory.js +61 -0
  236. package/export/typechain/factories/Deposit__factory.js +103 -0
  237. package/export/typechain/factories/DonationVault__factory.js +139 -0
  238. package/export/typechain/factories/ERC165__factory.js +38 -0
  239. package/export/typechain/factories/ERC1967Proxy__factory.js +111 -0
  240. package/export/typechain/factories/ERC1967Upgrade__factory.js +64 -0
  241. package/export/typechain/factories/ERC20WithPermit__factory.js +524 -0
  242. package/export/typechain/factories/ERC721__factory.js +388 -0
  243. package/export/typechain/factories/EcdsaAuthorization__factory.js +211 -0
  244. package/export/typechain/factories/EcdsaDkgValidator__factory.js +441 -0
  245. package/export/typechain/factories/EcdsaDkg__factory.js +192 -0
  246. package/export/typechain/factories/EcdsaInactivity__factory.js +134 -0
  247. package/export/typechain/factories/Fraud__factory.js +117 -0
  248. package/export/typechain/factories/Governable__factory.js +64 -0
  249. package/export/typechain/factories/HeartbeatStub__factory.js +61 -0
  250. package/export/typechain/factories/IApplication__factory.js +152 -0
  251. package/export/typechain/factories/IApproveAndCall__factory.js +48 -0
  252. package/export/typechain/factories/IBeacon__factory.js +32 -0
  253. package/export/typechain/factories/IERC165__factory.js +38 -0
  254. package/export/typechain/factories/IERC1822Proxiable__factory.js +32 -0
  255. package/export/typechain/factories/IERC20Metadata__factory.js +241 -0
  256. package/export/typechain/factories/IERC20WithPermit__factory.js +389 -0
  257. package/export/typechain/factories/IERC20__factory.js +202 -0
  258. package/export/typechain/factories/IERC721Metadata__factory.js +349 -0
  259. package/export/typechain/factories/IERC721Receiver__factory.js +53 -0
  260. package/export/typechain/factories/IERC721__factory.js +304 -0
  261. package/export/typechain/factories/IRandomBeaconConsumer__factory.js +37 -0
  262. package/export/typechain/factories/IRandomBeacon__factory.js +32 -0
  263. package/export/typechain/factories/IReceiveApproval__factory.js +47 -0
  264. package/export/typechain/factories/IReceiveBalanceApproval__factory.js +42 -0
  265. package/export/typechain/factories/IRelay__factory.js +45 -0
  266. package/export/typechain/factories/IStaking__factory.js +722 -0
  267. package/export/typechain/factories/IVault__factory.js +60 -0
  268. package/export/typechain/factories/IWalletOwner__factory.js +65 -0
  269. package/export/typechain/factories/IWalletRegistry__factory.js +138 -0
  270. package/export/typechain/factories/Initializable__factory.js +32 -0
  271. package/export/typechain/factories/MisfundRecovery__factory.js +145 -0
  272. package/export/typechain/factories/MovingFunds__factory.js +169 -0
  273. package/export/typechain/factories/Ownable__factory.js +71 -0
  274. package/export/typechain/factories/ProxyAdmin__factory.js +191 -0
  275. package/export/typechain/factories/Proxy__factory.js +27 -0
  276. package/export/typechain/factories/ReceiveApprovalStub__factory.js +127 -0
  277. package/export/typechain/factories/Redemption__factory.js +123 -0
  278. package/export/typechain/factories/Reimbursable__factory.js +58 -0
  279. package/export/typechain/factories/ReimbursementPool__factory.js +350 -0
  280. package/export/typechain/factories/Rewards__factory.js +117 -0
  281. package/export/typechain/factories/SortitionPool__factory.js +610 -0
  282. package/export/typechain/factories/SortitionTree__factory.js +149 -0
  283. package/export/typechain/factories/TBTCVault__factory.js +480 -0
  284. package/export/typechain/factories/TBTC__factory.js +564 -0
  285. package/export/typechain/factories/TestERC20__factory.js +539 -0
  286. package/export/typechain/factories/TestERC721__factory.js +421 -0
  287. package/export/typechain/factories/TestEcdsaLib__factory.js +66 -0
  288. package/export/typechain/factories/TestRelay__factory.js +94 -0
  289. package/export/typechain/factories/TransparentUpgradeableProxy__factory.js +186 -0
  290. package/export/typechain/factories/VendingMachine__factory.js +549 -0
  291. package/export/typechain/factories/WalletRegistry__factory.js +1919 -0
  292. package/export/typechain/factories/Wallets__factory.js +143 -0
  293. package/export/typechain/index.js +132 -0
  294. package/export.json +15932 -503
  295. package/package.json +47 -26
  296. package/artifacts/solcInputs/7cc3eda3cb3ff2522d18b5e7b31ea228.json +0 -104
@@ -0,0 +1,1020 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ // ██████████████ ▐████▌ ██████████████
4
+ // ██████████████ ▐████▌ ██████████████
5
+ // ▐████▌ ▐████▌
6
+ // ▐████▌ ▐████▌
7
+ // ██████████████ ▐████▌ ██████████████
8
+ // ██████████████ ▐████▌ ██████████████
9
+ // ▐████▌ ▐████▌
10
+ // ▐████▌ ▐████▌
11
+ // ▐████▌ ▐████▌
12
+ // ▐████▌ ▐████▌
13
+ // ▐████▌ ▐████▌
14
+ // ▐████▌ ▐████▌
15
+
16
+ pragma solidity ^0.8.9;
17
+
18
+ import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
19
+ import {BytesLib} from "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol";
20
+
21
+ import "./BitcoinTx.sol";
22
+ import "./BridgeState.sol";
23
+ import "./Wallets.sol";
24
+
25
+ import "../bank/Bank.sol";
26
+
27
+ /// @notice Aggregates functions common to the redemption transaction proof
28
+ /// validation and to the moving funds transaction proof validation.
29
+ library OutboundTx {
30
+ using BTCUtils for bytes;
31
+
32
+ /// @notice Checks whether an outbound Bitcoin transaction performed from
33
+ /// the given wallet has an input vector that contains a single
34
+ /// input referring to the wallet's main UTXO. Marks that main UTXO
35
+ /// as correctly spent if the validation succeeds. Reverts otherwise.
36
+ /// There are two outbound transactions from a wallet possible: a
37
+ /// redemption transaction or a moving funds to another wallet
38
+ /// transaction.
39
+ /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input
40
+ /// vector. This function assumes vector's structure is valid so it
41
+ /// must be validated using e.g. `BTCUtils.validateVin` function
42
+ /// before it is passed here.
43
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
44
+ /// the Ethereum chain.
45
+ function processWalletOutboundTxInput(
46
+ BridgeState.Storage storage self,
47
+ bytes memory walletOutboundTxInputVector,
48
+ BitcoinTx.UTXO calldata mainUtxo
49
+ ) internal {
50
+ // Assert that the single outbound transaction input actually
51
+ // refers to the wallet's main UTXO.
52
+ (
53
+ bytes32 outpointTxHash,
54
+ uint32 outpointIndex
55
+ ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);
56
+ require(
57
+ mainUtxo.txHash == outpointTxHash &&
58
+ mainUtxo.txOutputIndex == outpointIndex,
59
+ "Outbound transaction input must point to the wallet's main UTXO"
60
+ );
61
+
62
+ // Main UTXO used as an input, mark it as spent.
63
+ self.spentMainUTXOs[
64
+ uint256(
65
+ keccak256(
66
+ abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)
67
+ )
68
+ )
69
+ ] = true;
70
+ }
71
+
72
+ /// @notice Parses the input vector of an outbound Bitcoin transaction
73
+ /// performed from the given wallet. It extracts the single input
74
+ /// then the transaction hash and output index from its outpoint.
75
+ /// There are two outbound transactions from a wallet possible: a
76
+ /// redemption transaction or a moving funds to another wallet
77
+ /// transaction.
78
+ /// @param walletOutboundTxInputVector Bitcoin outbound transaction input
79
+ /// vector. This function assumes vector's structure is valid so it
80
+ /// must be validated using e.g. `BTCUtils.validateVin` function
81
+ /// before it is passed here.
82
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
83
+ /// pointed in the input's outpoint.
84
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
85
+ /// which is pointed in the input's outpoint.
86
+ function parseWalletOutboundTxInput(
87
+ bytes memory walletOutboundTxInputVector
88
+ ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {
89
+ // To determine the total number of Bitcoin transaction inputs,
90
+ // we need to parse the compactSize uint (VarInt) the input vector is
91
+ // prepended by. That compactSize uint encodes the number of vector
92
+ // elements using the format presented in:
93
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
94
+ // We don't need asserting the compactSize uint is parseable since it
95
+ // was already checked during `validateVin` validation.
96
+ // See `BitcoinTx.inputVector` docs for more details.
97
+ (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();
98
+ require(
99
+ inputsCount == 1,
100
+ "Outbound transaction must have a single input"
101
+ );
102
+
103
+ bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);
104
+
105
+ outpointTxHash = input.extractInputTxIdLE();
106
+
107
+ outpointIndex = BTCUtils.reverseUint32(
108
+ uint32(input.extractTxIndexLE())
109
+ );
110
+
111
+ // There is only one input in the transaction. Input has an outpoint
112
+ // field that is a reference to the transaction being spent (see
113
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
114
+ // to spend (`outpointTxHash`) and the index of the specific output
115
+ // from that transaction (`outpointIndex`).
116
+ return (outpointTxHash, outpointIndex);
117
+ }
118
+ }
119
+
120
+ /// @title Bridge redemption
121
+ /// @notice The library handles the logic for redeeming Bitcoin balances from
122
+ /// the Bridge.
123
+ /// @dev To initiate a redemption, a user with a Bank balance supplies
124
+ /// a Bitcoin address. Then, the system calculates the redemption fee, and
125
+ /// releases balance to the provided Bitcoin address. Just like in case of
126
+ /// sweeps of revealed deposits, redemption requests are processed in
127
+ /// batches and require SPV proof to be submitted to the Bridge.
128
+ library Redemption {
129
+ using BridgeState for BridgeState.Storage;
130
+ using Wallets for BridgeState.Storage;
131
+ using BitcoinTx for BridgeState.Storage;
132
+
133
+ using BTCUtils for bytes;
134
+ using BytesLib for bytes;
135
+
136
+ /// @notice Represents a redemption request.
137
+ struct RedemptionRequest {
138
+ // ETH address of the redeemer who created the request.
139
+ address redeemer;
140
+ // Requested TBTC amount in satoshi.
141
+ uint64 requestedAmount;
142
+ // Treasury TBTC fee in satoshi at the moment of request creation.
143
+ uint64 treasuryFee;
144
+ // Transaction maximum BTC fee in satoshi at the moment of request
145
+ // creation.
146
+ uint64 txMaxFee;
147
+ // UNIX timestamp the request was created at.
148
+ uint32 requestedAt;
149
+ // This struct doesn't contain `__gap` property as the structure is stored
150
+ // in a mapping, mappings store values in different slots and they are
151
+ // not contiguous with other values.
152
+ }
153
+
154
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
155
+ /// outputs processing.
156
+ struct RedemptionTxOutputsInfo {
157
+ // Total TBTC value in satoshi that should be burned by the Bridge.
158
+ // It includes the total amount of all BTC redeemed in the transaction
159
+ // and the fee paid to BTC miners for the redemption transaction.
160
+ uint64 totalBurnableValue;
161
+ // Total TBTC value in satoshi that should be transferred to
162
+ // the treasury. It is a sum of all treasury fees paid by all
163
+ // redeemers included in the redemption transaction.
164
+ uint64 totalTreasuryFee;
165
+ // Index of the change output. The change output becomes
166
+ // the new main wallet's UTXO.
167
+ uint32 changeIndex;
168
+ // Value in satoshi of the change output.
169
+ uint64 changeValue;
170
+ // This struct doesn't contain `__gap` property as the structure is not
171
+ // stored, it is used as a function's memory argument.
172
+ }
173
+
174
+ /// @notice Represents temporary information needed during the processing of
175
+ /// the redemption Bitcoin transaction outputs. This structure is an
176
+ /// internal one and should not be exported outside of the redemption
177
+ /// transaction processing code.
178
+ /// @dev Allows to mitigate "stack too deep" errors on EVM.
179
+ struct RedemptionTxOutputsProcessingInfo {
180
+ // The first output starting index in the transaction.
181
+ uint256 outputStartingIndex;
182
+ // The number of outputs in the transaction.
183
+ uint256 outputsCount;
184
+ // P2PKH script for the wallet. Needed to determine the change output.
185
+ bytes32 walletP2PKHScriptKeccak;
186
+ // P2WPKH script for the wallet. Needed to determine the change output.
187
+ bytes32 walletP2WPKHScriptKeccak;
188
+ // This struct doesn't contain `__gap` property as the structure is not
189
+ // stored, it is used as a function's memory argument.
190
+ }
191
+
192
+ event RedemptionRequested(
193
+ bytes20 indexed walletPubKeyHash,
194
+ bytes redeemerOutputScript,
195
+ address indexed redeemer,
196
+ uint64 requestedAmount,
197
+ uint64 treasuryFee,
198
+ uint64 txMaxFee
199
+ );
200
+
201
+ event RedemptionsCompleted(
202
+ bytes20 indexed walletPubKeyHash,
203
+ bytes32 redemptionTxHash
204
+ );
205
+
206
+ event RedemptionTimedOut(
207
+ bytes20 indexed walletPubKeyHash,
208
+ bytes redeemerOutputScript
209
+ );
210
+
211
+ /// @notice Requests redemption of the given amount from the specified
212
+ /// wallet to the redeemer Bitcoin output script.
213
+ /// This function handles the simplest case, where balance owner is
214
+ /// the redeemer.
215
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
216
+ /// using Bitcoin HASH160 over the compressed ECDSA public key).
217
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
218
+ /// the Ethereum chain.
219
+ /// @param balanceOwner The address of the Bank balance owner whose balance
220
+ /// is getting redeemed. Balance owner address is stored as
221
+ /// a redemeer address who will be able co claim back the Bank
222
+ /// balance if anything goes wrong during the redemption.
223
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
224
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
225
+ /// redeemed BTC.
226
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
227
+ /// that is taken from the `balanceOwner` upon request.
228
+ /// Once the request is handled, the actual amount of BTC locked
229
+ /// on the redeemer output script will be always lower than this value
230
+ /// since the treasury and Bitcoin transaction fees must be incurred.
231
+ /// The minimal amount satisfying the request can be computed as:
232
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
233
+ /// Fees values are taken at the moment of request creation.
234
+ /// @dev Requirements:
235
+ /// - Wallet behind `walletPubKeyHash` must be live,
236
+ /// - `mainUtxo` components must point to the recent main UTXO
237
+ /// of the given wallet, as currently known on the Ethereum chain,
238
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
239
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
240
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
241
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
242
+ /// used for only one pending request at the same time,
243
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
244
+ /// - Balance owner must make an allowance in the Bank that the Bridge
245
+ /// contract can spend the given `amount`.
246
+ function requestRedemption(
247
+ BridgeState.Storage storage self,
248
+ bytes20 walletPubKeyHash,
249
+ BitcoinTx.UTXO calldata mainUtxo,
250
+ address balanceOwner,
251
+ bytes calldata redeemerOutputScript,
252
+ uint64 amount
253
+ ) external {
254
+ requestRedemption(
255
+ self,
256
+ walletPubKeyHash,
257
+ mainUtxo,
258
+ balanceOwner,
259
+ balanceOwner,
260
+ redeemerOutputScript,
261
+ amount
262
+ );
263
+ }
264
+
265
+ /// @notice Requests redemption of the given amount from the specified
266
+ /// wallet to the redeemer Bitcoin output script. Used by
267
+ /// `Bridge.receiveBalanceApproval`. Can handle more complex cases
268
+ /// where balance owner may be someone else than the redeemer.
269
+ /// @param balanceOwner The address of the Bank balance owner whose balance
270
+ /// is getting redeemed.
271
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
272
+ /// that is taken from the `balanceOwner` upon request.
273
+ /// Once the request is handled, the actual amount of BTC locked
274
+ /// on the redeemer output script will be always lower than this value
275
+ /// since the treasury and Bitcoin transaction fees must be incurred.
276
+ /// The minimal amount satisfying the request can be computed as:
277
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
278
+ /// Fees values are taken at the moment of request creation.
279
+ /// @param redemptionData ABI-encoded redemption data:
280
+ /// [
281
+ /// address redeemer,
282
+ /// bytes20 walletPubKeyHash,
283
+ /// bytes32 mainUtxoTxHash,
284
+ /// uint32 mainUtxoTxOutputIndex,
285
+ /// uint64 mainUtxoTxOutputValue,
286
+ /// bytes redeemerOutputScript
287
+ /// ]
288
+ ///
289
+ /// - redeemer: The Ethereum address of the redeemer who will be able
290
+ /// to claim Bank balance if anything goes wrong during the redemption.
291
+ /// In the most basic case, when someone redeems their Bitcoin
292
+ /// balance from the Bank, `balanceOwner` is the same as `redemeer`.
293
+ /// However, when a Vault is redeeming part of its balance for some
294
+ /// redeemer address (for example, someone who has earlier deposited
295
+ /// into that Vault), `balanceOwner` is the Vault, and `redemeer` is
296
+ /// the address for which the vault is redeeming its balance to,
297
+ /// - walletPubKeyHash: The 20-byte wallet public key hash (computed
298
+ /// using Bitcoin HASH160 over the compressed ECDSA public key),
299
+ /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as
300
+ /// currently known on the Ethereum chain,
301
+ /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output
302
+ /// index, as currently known on Ethereum chain,
303
+ /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output
304
+ /// value, as currently known on Ethereum chain,
305
+ /// - redeemerOutputScript The redeemer's length-prefixed output
306
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
307
+ /// redeemed BTC.
308
+ /// @dev Requirements:
309
+ /// - Wallet behind `walletPubKeyHash` must be live,
310
+ /// - `mainUtxo*` components must point to the recent main UTXO
311
+ /// of the given wallet, as currently known on the Ethereum chain,
312
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
313
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
314
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
315
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
316
+ /// used for only one pending request at the same time,
317
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
318
+ /// - Balance owner must make an allowance in the Bank that the Bridge
319
+ /// contract can spend the given `amount`.
320
+ function requestRedemption(
321
+ BridgeState.Storage storage self,
322
+ address balanceOwner,
323
+ uint64 amount,
324
+ bytes calldata redemptionData
325
+ ) external {
326
+ (
327
+ address redeemer,
328
+ bytes20 walletPubKeyHash,
329
+ bytes32 mainUtxoTxHash,
330
+ uint32 mainUtxoTxOutputIndex,
331
+ uint64 mainUtxoTxOutputValue,
332
+ bytes memory redeemerOutputScript
333
+ ) = abi.decode(
334
+ redemptionData,
335
+ (address, bytes20, bytes32, uint32, uint64, bytes)
336
+ );
337
+
338
+ requestRedemption(
339
+ self,
340
+ walletPubKeyHash,
341
+ BitcoinTx.UTXO(
342
+ mainUtxoTxHash,
343
+ mainUtxoTxOutputIndex,
344
+ mainUtxoTxOutputValue
345
+ ),
346
+ balanceOwner,
347
+ redeemer,
348
+ redeemerOutputScript,
349
+ amount
350
+ );
351
+ }
352
+
353
+ /// @notice Requests redemption of the given amount from the specified
354
+ /// wallet to the redeemer Bitcoin output script.
355
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
356
+ /// using Bitcoin HASH160 over the compressed ECDSA public key).
357
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
358
+ /// the Ethereum chain.
359
+ /// @param balanceOwner The address of the Bank balance owner whose balance
360
+ /// is getting redeemed.
361
+ /// @param redeemer The Ethereum address of the redeemer who will be able to
362
+ /// claim Bank balance if anything goes wrong during the redemption.
363
+ /// In the most basic case, when someone redeems their Bitcoin
364
+ /// balance from the Bank, `balanceOwner` is the same as `redeemer`.
365
+ /// However, when a Vault is redeeming part of its balance for some
366
+ /// redeemer address (for example, someone who has earlier deposited
367
+ /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is
368
+ /// the address for which the vault is redeeming its balance to.
369
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
370
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
371
+ /// redeemed BTC.
372
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
373
+ /// that is taken from the `balanceOwner` upon request.
374
+ /// Once the request is handled, the actual amount of BTC locked
375
+ /// on the redeemer output script will be always lower than this value
376
+ /// since the treasury and Bitcoin transaction fees must be incurred.
377
+ /// The minimal amount satisfying the request can be computed as:
378
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
379
+ /// Fees values are taken at the moment of request creation.
380
+ /// @dev Requirements:
381
+ /// - Wallet behind `walletPubKeyHash` must be live,
382
+ /// - `mainUtxo` components must point to the recent main UTXO
383
+ /// of the given wallet, as currently known on the Ethereum chain,
384
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
385
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
386
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
387
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
388
+ /// used for only one pending request at the same time,
389
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
390
+ /// - Balance owner must make an allowance in the Bank that the Bridge
391
+ /// contract can spend the given `amount`.
392
+ function requestRedemption(
393
+ BridgeState.Storage storage self,
394
+ bytes20 walletPubKeyHash,
395
+ BitcoinTx.UTXO memory mainUtxo,
396
+ address balanceOwner,
397
+ address redeemer,
398
+ bytes memory redeemerOutputScript,
399
+ uint64 amount
400
+ ) internal {
401
+ Wallets.Wallet storage wallet = self.registeredWallets[
402
+ walletPubKeyHash
403
+ ];
404
+
405
+ require(
406
+ wallet.state == Wallets.WalletState.Live,
407
+ "Wallet must be in Live state"
408
+ );
409
+
410
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
411
+ require(
412
+ mainUtxoHash != bytes32(0),
413
+ "No main UTXO for the given wallet"
414
+ );
415
+ require(
416
+ keccak256(
417
+ abi.encodePacked(
418
+ mainUtxo.txHash,
419
+ mainUtxo.txOutputIndex,
420
+ mainUtxo.txOutputValue
421
+ )
422
+ ) == mainUtxoHash,
423
+ "Invalid main UTXO data"
424
+ );
425
+
426
+ // Validate if redeemer output script is a correct standard type
427
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
428
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
429
+ // a function extracts the payload properly only from standard outputs
430
+ // so if it succeeds, we have a guarantee the redeemer output script
431
+ // is proper. Worth to note `extractHash` ignores the value at all
432
+ // so this is why we can use 0 safely. This way of validation is the
433
+ // same as in tBTC v1.
434
+ bytes memory redeemerOutputScriptPayload = abi
435
+ .encodePacked(bytes8(0), redeemerOutputScript)
436
+ .extractHash();
437
+ require(
438
+ redeemerOutputScriptPayload.length > 0,
439
+ "Redeemer output script must be a standard type"
440
+ );
441
+ // Check if the redeemer output script payload does not point to the
442
+ // wallet public key hash.
443
+ require(
444
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
445
+ keccak256(redeemerOutputScriptPayload),
446
+ "Redeemer output script must not point to the wallet PKH"
447
+ );
448
+
449
+ require(
450
+ amount >= self.redemptionDustThreshold,
451
+ "Redemption amount too small"
452
+ );
453
+
454
+ // The redemption key is built on top of the wallet public key hash
455
+ // and redeemer output script pair. That means there can be only one
456
+ // request asking for redemption from the given wallet to the given
457
+ // BTC script at the same time.
458
+ uint256 redemptionKey = uint256(
459
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
460
+ );
461
+
462
+ // Check if given redemption key is not used by a pending redemption.
463
+ // There is no need to check for existence in `timedOutRedemptions`
464
+ // since the wallet's state is changed to other than Live after
465
+ // first time out is reported so making new requests is not possible.
466
+ // slither-disable-next-line incorrect-equality
467
+ require(
468
+ self.pendingRedemptions[redemptionKey].requestedAt == 0,
469
+ "There is a pending redemption request from this wallet to the same address"
470
+ );
471
+
472
+ // No need to check whether `amount - treasuryFee - txMaxFee > 0`
473
+ // since the `redemptionDustThreshold` should force that condition
474
+ // to be always true.
475
+ uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0
476
+ ? amount / self.redemptionTreasuryFeeDivisor
477
+ : 0;
478
+ uint64 txMaxFee = self.redemptionTxMaxFee;
479
+
480
+ // The main wallet UTXO's value doesn't include all pending redemptions.
481
+ // To determine if the requested redemption can be performed by the
482
+ // wallet we need to subtract the total value of all pending redemptions
483
+ // from that wallet's main UTXO value. Given that the treasury fee is
484
+ // not redeemed from the wallet, we are subtracting it.
485
+ wallet.pendingRedemptionsValue += amount - treasuryFee;
486
+ require(
487
+ mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
488
+ "Insufficient wallet funds"
489
+ );
490
+
491
+ self.pendingRedemptions[redemptionKey] = RedemptionRequest(
492
+ redeemer,
493
+ amount,
494
+ treasuryFee,
495
+ txMaxFee,
496
+ /* solhint-disable-next-line not-rely-on-time */
497
+ uint32(block.timestamp)
498
+ );
499
+
500
+ emit RedemptionRequested(
501
+ walletPubKeyHash,
502
+ redeemerOutputScript,
503
+ redeemer,
504
+ amount,
505
+ treasuryFee,
506
+ txMaxFee
507
+ );
508
+
509
+ self.bank.transferBalanceFrom(balanceOwner, address(this), amount);
510
+ }
511
+
512
+ /// @notice Used by the wallet to prove the BTC redemption transaction
513
+ /// and to make the necessary bookkeeping. Redemption is only
514
+ /// accepted if it satisfies SPV proof.
515
+ ///
516
+ /// The function is performing Bank balance updates by burning
517
+ /// the total redeemed Bitcoin amount from Bridge balance and
518
+ /// transferring the treasury fee sum to the treasury address.
519
+ ///
520
+ /// It is possible to prove the given redemption only one time.
521
+ /// @param redemptionTx Bitcoin redemption transaction data.
522
+ /// @param redemptionProof Bitcoin redemption proof data.
523
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
524
+ /// the Ethereum chain.
525
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
526
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
527
+ /// performed the redemption transaction.
528
+ /// @dev Requirements:
529
+ /// - `redemptionTx` components must match the expected structure. See
530
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
531
+ /// correspond to appropriate Bitcoin transaction fields to produce
532
+ /// a provable transaction hash,
533
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
534
+ /// exactly 1 input that refers to the wallet's main UTXO. That
535
+ /// transaction should have 1..n outputs handling existing pending
536
+ /// redemption requests or pointing to reported timed out requests.
537
+ /// There can be also 1 optional output representing the
538
+ /// change and pointing back to the 20-byte wallet public key hash.
539
+ /// The change should be always present if the redeemed value sum
540
+ /// is lower than the total wallet's BTC balance,
541
+ /// - `redemptionProof` components must match the expected structure.
542
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
543
+ /// field must contain a valid number of block headers, not less
544
+ /// than the `txProofDifficultyFactor` contract constant,
545
+ /// - `mainUtxo` components must point to the recent main UTXO
546
+ /// of the given wallet, as currently known on the Ethereum chain.
547
+ /// Additionally, the recent main UTXO on Ethereum must be set,
548
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
549
+ /// as transaction single input.
550
+ /// Other remarks:
551
+ /// - Putting the change output as the first transaction output can
552
+ /// save some gas because the output processing loop begins each
553
+ /// iteration by checking whether the given output is the change
554
+ /// thus uses some gas for making the comparison. Once the change
555
+ /// is identified, that check is omitted in further iterations.
556
+ function submitRedemptionProof(
557
+ BridgeState.Storage storage self,
558
+ BitcoinTx.Info calldata redemptionTx,
559
+ BitcoinTx.Proof calldata redemptionProof,
560
+ BitcoinTx.UTXO calldata mainUtxo,
561
+ bytes20 walletPubKeyHash
562
+ ) external {
563
+ // Wallet state validation is performed in the `resolveRedeemingWallet`
564
+ // function.
565
+
566
+ // The actual transaction proof is performed here. After that point, we
567
+ // can assume the transaction happened on Bitcoin chain and has
568
+ // a sufficient number of confirmations as determined by
569
+ // `txProofDifficultyFactor` constant.
570
+ bytes32 redemptionTxHash = self.validateProof(
571
+ redemptionTx,
572
+ redemptionProof
573
+ );
574
+
575
+ Wallets.Wallet storage wallet = resolveRedeemingWallet(
576
+ self,
577
+ walletPubKeyHash,
578
+ mainUtxo
579
+ );
580
+
581
+ // Process the redemption transaction input. Specifically, check if it
582
+ // refers to the expected wallet's main UTXO.
583
+ OutboundTx.processWalletOutboundTxInput(
584
+ self,
585
+ redemptionTx.inputVector,
586
+ mainUtxo
587
+ );
588
+
589
+ // Process redemption transaction outputs to extract some info required
590
+ // for further processing.
591
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
592
+ self,
593
+ redemptionTx.outputVector,
594
+ walletPubKeyHash
595
+ );
596
+
597
+ if (outputsInfo.changeValue > 0) {
598
+ // If the change value is grater than zero, it means the change
599
+ // output exists and can be used as new wallet's main UTXO.
600
+ wallet.mainUtxoHash = keccak256(
601
+ abi.encodePacked(
602
+ redemptionTxHash,
603
+ outputsInfo.changeIndex,
604
+ outputsInfo.changeValue
605
+ )
606
+ );
607
+ } else {
608
+ // If the change value is zero, it means the change output doesn't
609
+ // exists and no funds left on the wallet. Delete the main UTXO
610
+ // for that wallet to represent that state in a proper way.
611
+ delete wallet.mainUtxoHash;
612
+ }
613
+
614
+ wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
615
+
616
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
617
+
618
+ self.bank.decreaseBalance(outputsInfo.totalBurnableValue);
619
+ self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);
620
+ }
621
+
622
+ /// @notice Resolves redeeming wallet based on the provided wallet public
623
+ /// key hash. Validates the wallet state and current main UTXO, as
624
+ /// currently known on the Ethereum chain.
625
+ /// @param walletPubKeyHash public key hash of the wallet proving the sweep
626
+ /// Bitcoin transaction.
627
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
628
+ /// the Ethereum chain.
629
+ /// @return wallet Data of the sweeping wallet.
630
+ /// @dev Requirements:
631
+ /// - Sweeping wallet must be either in Live or MovingFunds state,
632
+ /// - Main UTXO of the redeeming wallet must exists in the storage,
633
+ /// - The passed `mainUTXO` parameter must be equal to the stored one.
634
+ function resolveRedeemingWallet(
635
+ BridgeState.Storage storage self,
636
+ bytes20 walletPubKeyHash,
637
+ BitcoinTx.UTXO calldata mainUtxo
638
+ ) internal view returns (Wallets.Wallet storage wallet) {
639
+ wallet = self.registeredWallets[walletPubKeyHash];
640
+
641
+ // Assert that main UTXO for passed wallet exists in storage.
642
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
643
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
644
+
645
+ // Assert that passed main UTXO parameter is the same as in storage and
646
+ // can be used for further processing.
647
+ require(
648
+ keccak256(
649
+ abi.encodePacked(
650
+ mainUtxo.txHash,
651
+ mainUtxo.txOutputIndex,
652
+ mainUtxo.txOutputValue
653
+ )
654
+ ) == mainUtxoHash,
655
+ "Invalid main UTXO data"
656
+ );
657
+
658
+ Wallets.WalletState walletState = wallet.state;
659
+ require(
660
+ walletState == Wallets.WalletState.Live ||
661
+ walletState == Wallets.WalletState.MovingFunds,
662
+ "Wallet must be in Live or MovingFunds state"
663
+ );
664
+ }
665
+
666
+ /// @notice Processes the Bitcoin redemption transaction output vector.
667
+ /// It extracts each output and tries to identify it as a pending
668
+ /// redemption request, reported timed out request, or change.
669
+ /// Reverts if one of the outputs cannot be recognized properly.
670
+ /// This function also marks each request as processed by removing
671
+ /// them from `pendingRedemptions` mapping.
672
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
673
+ /// vector. This function assumes vector's structure is valid so it
674
+ /// must be validated using e.g. `BTCUtils.validateVout` function
675
+ /// before it is passed here.
676
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
677
+ // HASH160 over the compressed ECDSA public key) of the wallet which
678
+ /// performed the redemption transaction.
679
+ /// @return info Outcomes of the processing.
680
+ function processRedemptionTxOutputs(
681
+ BridgeState.Storage storage self,
682
+ bytes memory redemptionTxOutputVector,
683
+ bytes20 walletPubKeyHash
684
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
685
+ // Determining the total number of redemption transaction outputs in
686
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
687
+ // docs for more details.
688
+ (
689
+ uint256 outputsCompactSizeUintLength,
690
+ uint256 outputsCount
691
+ ) = redemptionTxOutputVector.parseVarInt();
692
+
693
+ // To determine the first output starting index, we must jump over
694
+ // the compactSize uint which prepends the output vector. One byte
695
+ // must be added because `BtcUtils.parseVarInt` does not include
696
+ // compactSize uint tag in the returned length.
697
+ //
698
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
699
+ // returns `0`, so we jump over one byte of compactSize uint.
700
+ //
701
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
702
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
703
+ // tag byte included) so we need to jump over 1+2 bytes of
704
+ // compactSize uint.
705
+ //
706
+ // Please refer `BTCUtils` library and compactSize uint
707
+ // docs in `BitcoinTx` library for more details.
708
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
709
+
710
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
711
+ // scripts that can be used to lock the change. This is done upfront to
712
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
713
+ //
714
+ // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.
715
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
716
+ // - 0x19: Byte length of the entire script
717
+ // - 0x76: OP_DUP
718
+ // - 0xa9: OP_HASH160
719
+ // - 0x14: Byte length of the public key hash
720
+ // - 0x88: OP_EQUALVERIFY
721
+ // - 0xac: OP_CHECKSIG
722
+ // which matches the P2PKH structure as per:
723
+ // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
724
+ bytes32 walletP2PKHScriptKeccak = keccak256(
725
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
726
+ );
727
+ // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.
728
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
729
+ // - 0x16: Byte length of the entire script
730
+ // - 0x00: OP_0
731
+ // - 0x14: Byte length of the public key hash
732
+ // which matches the P2WPKH structure as per:
733
+ // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
734
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
735
+ abi.encodePacked(hex"160014", walletPubKeyHash)
736
+ );
737
+
738
+ return
739
+ processRedemptionTxOutputs(
740
+ self,
741
+ redemptionTxOutputVector,
742
+ walletPubKeyHash,
743
+ RedemptionTxOutputsProcessingInfo(
744
+ outputStartingIndex,
745
+ outputsCount,
746
+ walletP2PKHScriptKeccak,
747
+ walletP2WPKHScriptKeccak
748
+ )
749
+ );
750
+ }
751
+
752
+ /// @notice Processes all outputs from the redemption transaction. Tries to
753
+ /// identify output as a change output, pending redemption request
754
+ // or reported redemption. Reverts if one of the outputs cannot be
755
+ /// recognized properly. Marks each request as processed by removing
756
+ /// them from `pendingRedemptions` mapping.
757
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
758
+ /// vector. This function assumes vector's structure is valid so it
759
+ /// must be validated using e.g. `BTCUtils.validateVout` function
760
+ /// before it is passed here.
761
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
762
+ // HASH160 over the compressed ECDSA public key) of the wallet which
763
+ /// performed the redemption transaction.
764
+ /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output
765
+ /// starting index, the number of outputs and possible wallet change
766
+ /// P2PKH and P2WPKH scripts.
767
+ function processRedemptionTxOutputs(
768
+ BridgeState.Storage storage self,
769
+ bytes memory redemptionTxOutputVector,
770
+ bytes20 walletPubKeyHash,
771
+ RedemptionTxOutputsProcessingInfo memory processInfo
772
+ ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {
773
+ // Helper flag indicating whether there was at least one redemption
774
+ // output present (redemption must be either pending or reported as
775
+ // timed out).
776
+ bool redemptionPresent = false;
777
+
778
+ // Outputs processing loop.
779
+ for (uint256 i = 0; i < processInfo.outputsCount; i++) {
780
+ // TODO: Check if we can optimize gas costs by adding
781
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
782
+ // in order to avoid allocating bytes in memory.
783
+ // https://github.com/keep-network/tbtc-v2/issues/257
784
+ uint256 outputLength = redemptionTxOutputVector
785
+ .determineOutputLengthAt(processInfo.outputStartingIndex);
786
+ bytes memory output = redemptionTxOutputVector.slice(
787
+ processInfo.outputStartingIndex,
788
+ outputLength
789
+ );
790
+
791
+ // Extract the value from given output.
792
+ uint64 outputValue = output.extractValue();
793
+ // The output consists of an 8-byte value and a variable length
794
+ // script. To extract that script we slice the output starting from
795
+ // 9th byte until the end.
796
+ bytes memory outputScript = output.slice(8, output.length - 8);
797
+
798
+ if (
799
+ resultInfo.changeValue == 0 &&
800
+ (keccak256(outputScript) ==
801
+ processInfo.walletP2PKHScriptKeccak ||
802
+ keccak256(outputScript) ==
803
+ processInfo.walletP2WPKHScriptKeccak) &&
804
+ outputValue > 0
805
+ ) {
806
+ // If we entered here, that means the change output with a
807
+ // proper non-zero value was found.
808
+ resultInfo.changeIndex = uint32(i);
809
+ resultInfo.changeValue = outputValue;
810
+ } else {
811
+ // If we entered here, that the means the given output is
812
+ // supposed to represent a redemption.
813
+ (
814
+ uint64 burnableValue,
815
+ uint64 treasuryFee
816
+ ) = processNonChangeRedemptionTxOutput(
817
+ self,
818
+ walletPubKeyHash,
819
+ outputScript,
820
+ outputValue
821
+ );
822
+ resultInfo.totalBurnableValue += burnableValue;
823
+ resultInfo.totalTreasuryFee += treasuryFee;
824
+ redemptionPresent = true;
825
+ }
826
+
827
+ // Make the `outputStartingIndex` pointing to the next output by
828
+ // increasing it by current output's length.
829
+ processInfo.outputStartingIndex += outputLength;
830
+ }
831
+
832
+ // Protect against the cases when there is only a single change output
833
+ // referring back to the wallet PKH and just burning main UTXO value
834
+ // for transaction fees.
835
+ require(
836
+ redemptionPresent,
837
+ "Redemption transaction must process at least one redemption"
838
+ );
839
+ }
840
+
841
+ /// @notice Processes a single redemption transaction output. Tries to
842
+ /// identify output as a pending redemption request or reported
843
+ /// redemption timeout. Output script passed to this function must
844
+ /// not be the change output. Such output needs to be identified
845
+ /// separately before calling this function.
846
+ /// Reverts if output is neither requested pending redemption nor
847
+ /// requested and reported timed-out redemption.
848
+ /// This function also marks each pending request as processed by
849
+ /// removing them from `pendingRedemptions` mapping.
850
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
851
+ // HASH160 over the compressed ECDSA public key) of the wallet which
852
+ /// performed the redemption transaction.
853
+ /// @param outputScript Non-change output script to be processed.
854
+ /// @param outputValue Value of the output being processed.
855
+ /// @return burnableValue The value burnable as a result of processing this
856
+ /// single redemption output. This value needs to be summed up with
857
+ /// burnable values of all other outputs to evaluate total burnable
858
+ /// value for the entire redemption transaction. This value is 0
859
+ /// for a timed-out redemption request.
860
+ /// @return treasuryFee The treasury fee from this single redemption output.
861
+ /// This value needs to be summed up with treasury fees of all other
862
+ /// outputs to evaluate the total treasury fee for the entire
863
+ /// redemption transaction. This value is 0 for a timed-out
864
+ /// redemption request.
865
+ function processNonChangeRedemptionTxOutput(
866
+ BridgeState.Storage storage self,
867
+ bytes20 walletPubKeyHash,
868
+ bytes memory outputScript,
869
+ uint64 outputValue
870
+ ) internal returns (uint64 burnableValue, uint64 treasuryFee) {
871
+ // This function should be called only if the given output is
872
+ // supposed to represent a redemption. Build the redemption key
873
+ // to perform that check.
874
+ uint256 redemptionKey = uint256(
875
+ keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
876
+ );
877
+
878
+ if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {
879
+ // If we entered here, that means the output was identified
880
+ // as a pending redemption request.
881
+ RedemptionRequest storage request = self.pendingRedemptions[
882
+ redemptionKey
883
+ ];
884
+ // Compute the request's redeemable amount as the requested
885
+ // amount reduced by the treasury fee. The request's
886
+ // minimal amount is then the redeemable amount reduced by
887
+ // the maximum transaction fee.
888
+ uint64 redeemableAmount = request.requestedAmount -
889
+ request.treasuryFee;
890
+ // Output value must fit between the request's redeemable
891
+ // and minimal amounts to be deemed valid.
892
+ require(
893
+ redeemableAmount - request.txMaxFee <= outputValue &&
894
+ outputValue <= redeemableAmount,
895
+ "Output value is not within the acceptable range of the pending request"
896
+ );
897
+ // Add the redeemable amount to the total burnable value
898
+ // the Bridge will use to decrease its balance in the Bank.
899
+ burnableValue = redeemableAmount;
900
+ // Add the request's treasury fee to the total treasury fee
901
+ // value the Bridge will transfer to the treasury.
902
+ treasuryFee = request.treasuryFee;
903
+ // Request was properly handled so remove its redemption
904
+ // key from the mapping to make it reusable for further
905
+ // requests.
906
+ delete self.pendingRedemptions[redemptionKey];
907
+ } else {
908
+ // If we entered here, the output is not a redemption
909
+ // request but there is still a chance the given output is
910
+ // related to a reported timed out redemption request.
911
+ // If so, check if the output value matches the request
912
+ // amount to confirm this is an overdue request fulfillment
913
+ // then bypass this output and process the subsequent
914
+ // ones. That also means the wallet was already punished
915
+ // for the inactivity. Otherwise, just revert.
916
+ RedemptionRequest storage request = self.timedOutRedemptions[
917
+ redemptionKey
918
+ ];
919
+
920
+ require(
921
+ request.requestedAt != 0,
922
+ "Output is a non-requested redemption"
923
+ );
924
+
925
+ uint64 redeemableAmount = request.requestedAmount -
926
+ request.treasuryFee;
927
+
928
+ require(
929
+ redeemableAmount - request.txMaxFee <= outputValue &&
930
+ outputValue <= redeemableAmount,
931
+ "Output value is not within the acceptable range of the timed out request"
932
+ );
933
+ }
934
+ }
935
+
936
+ /// @notice Notifies that there is a pending redemption request associated
937
+ /// with the given wallet, that has timed out. The redemption
938
+ /// request is identified by the key built as
939
+ /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.
940
+ /// The results of calling this function:
941
+ /// - the pending redemptions value for the wallet will be decreased
942
+ /// by the requested amount (minus treasury fee),
943
+ /// - the tokens taken from the redeemer on redemption request will
944
+ /// be returned to the redeemer,
945
+ /// - the request will be moved from pending redemptions to
946
+ /// timed-out redemptions,
947
+ /// - if the state of the wallet is `Live` or `MovingFunds`, the
948
+ /// wallet operators will be slashed and the notifier will be
949
+ /// rewarded,
950
+ /// - if the state of wallet is `Live`, the wallet will be closed or
951
+ /// marked as `MovingFunds` (depending on the presence or absence
952
+ /// of the wallet's main UTXO) and the wallet will no longer be
953
+ /// marked as the active wallet (if it was marked as such).
954
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet.
955
+ /// @param walletMembersIDs Identifiers of the wallet signing group members.
956
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
957
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH).
958
+ /// @dev Requirements:
959
+ /// - The wallet must be in the Live or MovingFunds or Terminated state,
960
+ /// - The redemption request identified by `walletPubKeyHash` and
961
+ /// `redeemerOutputScript` must exist,
962
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
963
+ /// be exactly the same as the hash stored under `membersIdsHash`
964
+ /// for the given `walletID`. Those IDs are not directly stored
965
+ /// in the contract for gas efficiency purposes but they can be
966
+ /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
967
+ /// events of the `WalletRegistry` contract,
968
+ /// - The amount of time defined by `redemptionTimeout` must have
969
+ /// passed since the redemption was requested (the request must be
970
+ /// timed-out).
971
+ function notifyRedemptionTimeout(
972
+ BridgeState.Storage storage self,
973
+ bytes20 walletPubKeyHash,
974
+ uint32[] calldata walletMembersIDs,
975
+ bytes calldata redeemerOutputScript
976
+ ) external {
977
+ // Wallet state is validated in `notifyWalletRedemptionTimeout`.
978
+
979
+ uint256 redemptionKey = uint256(
980
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
981
+ );
982
+ Redemption.RedemptionRequest memory request = self.pendingRedemptions[
983
+ redemptionKey
984
+ ];
985
+
986
+ require(request.requestedAt > 0, "Redemption request does not exist");
987
+ require(
988
+ /* solhint-disable-next-line not-rely-on-time */
989
+ request.requestedAt + self.redemptionTimeout < block.timestamp,
990
+ "Redemption request has not timed out"
991
+ );
992
+
993
+ // Update the wallet's pending redemptions value
994
+ Wallets.Wallet storage wallet = self.registeredWallets[
995
+ walletPubKeyHash
996
+ ];
997
+ wallet.pendingRedemptionsValue -=
998
+ request.requestedAmount -
999
+ request.treasuryFee;
1000
+
1001
+ // It is worth noting that there is no need to check if
1002
+ // `timedOutRedemption` mapping already contains the given redemption
1003
+ // key. There is no possibility to re-use a key of a reported timed-out
1004
+ // redemption because the wallet responsible for causing the timeout is
1005
+ // moved to a state that prevents it to receive new redemption requests.
1006
+
1007
+ // Propagate timeout consequences to the wallet
1008
+ self.notifyWalletRedemptionTimeout(walletPubKeyHash, walletMembersIDs);
1009
+
1010
+ // Move the redemption from pending redemptions to timed-out redemptions
1011
+ self.timedOutRedemptions[redemptionKey] = request;
1012
+ delete self.pendingRedemptions[redemptionKey];
1013
+
1014
+ // slither-disable-next-line reentrancy-events
1015
+ emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
1016
+
1017
+ // Return the requested amount of tokens to the redeemer
1018
+ self.bank.transferBalance(request.redeemer, request.requestedAmount);
1019
+ }
1020
+ }