Complex classes like Wallet often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Wallet, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 33 | abstract class Wallet implements WalletInterface { |
||
| 34 | |||
| 35 | const WALLET_VERSION_V1 = 'v1'; |
||
| 36 | const WALLET_VERSION_V2 = 'v2'; |
||
| 37 | const WALLET_VERSION_V3 = 'v3'; |
||
| 38 | |||
| 39 | const CHAIN_BTC_DEFAULT = 0; |
||
| 40 | const CHAIN_BCC_DEFAULT = 1; |
||
| 41 | const CHAIN_BTC_SEGWIT = 2; |
||
| 42 | |||
| 43 | const BASE_FEE = 10000; |
||
| 44 | |||
| 45 | /** |
||
| 46 | * development / debug setting |
||
| 47 | * when getting a new derivation from the API, |
||
| 48 | * will verify address / redeeemScript with the values the API provides |
||
| 49 | */ |
||
| 50 | const VERIFY_NEW_DERIVATION = true; |
||
| 51 | |||
| 52 | /** |
||
| 53 | * @var BlocktrailSDKInterface |
||
| 54 | */ |
||
| 55 | protected $sdk; |
||
| 56 | |||
| 57 | /** |
||
| 58 | * @var string |
||
| 59 | */ |
||
| 60 | protected $identifier; |
||
| 61 | |||
| 62 | /** |
||
| 63 | * BIP32 master primary private key (m/) |
||
| 64 | * |
||
| 65 | * @var BIP32Key |
||
| 66 | */ |
||
| 67 | protected $primaryPrivateKey; |
||
| 68 | |||
| 69 | /** |
||
| 70 | * @var BIP32Key[] |
||
| 71 | */ |
||
| 72 | protected $primaryPublicKeys; |
||
| 73 | |||
| 74 | /** |
||
| 75 | * BIP32 master backup public key (M/) |
||
| 76 | |||
| 77 | * @var BIP32Key |
||
| 78 | */ |
||
| 79 | protected $backupPublicKey; |
||
| 80 | |||
| 81 | /** |
||
| 82 | * map of blocktrail BIP32 public keys |
||
| 83 | * keyed by key index |
||
| 84 | * path should be `M / key_index'` |
||
| 85 | * |
||
| 86 | * @var BIP32Key[] |
||
| 87 | */ |
||
| 88 | protected $blocktrailPublicKeys; |
||
| 89 | |||
| 90 | /** |
||
| 91 | * the 'Blocktrail Key Index' that is used for new addresses |
||
| 92 | * |
||
| 93 | * @var int |
||
| 94 | */ |
||
| 95 | protected $keyIndex; |
||
| 96 | |||
| 97 | /** |
||
| 98 | * 'bitcoin' |
||
| 99 | * |
||
| 100 | * @var string |
||
| 101 | */ |
||
| 102 | protected $network; |
||
| 103 | |||
| 104 | /** |
||
| 105 | * testnet yes / no |
||
| 106 | * |
||
| 107 | * @var bool |
||
| 108 | */ |
||
| 109 | protected $testnet; |
||
| 110 | |||
| 111 | /** |
||
| 112 | * cache of public keys, by path |
||
| 113 | * |
||
| 114 | * @var BIP32Key[] |
||
| 115 | */ |
||
| 116 | protected $pubKeys = []; |
||
| 117 | |||
| 118 | /** |
||
| 119 | * cache of address / redeemScript, by path |
||
| 120 | * |
||
| 121 | * @var string[][] [[address, redeemScript)], ] |
||
| 122 | */ |
||
| 123 | protected $derivations = []; |
||
| 124 | |||
| 125 | /** |
||
| 126 | * reverse cache of paths by address |
||
| 127 | * |
||
| 128 | * @var string[] |
||
| 129 | */ |
||
| 130 | protected $derivationsByAddress = []; |
||
| 131 | |||
| 132 | /** |
||
| 133 | * @var string |
||
| 134 | */ |
||
| 135 | protected $checksum; |
||
| 136 | |||
| 137 | /** |
||
| 138 | * @var bool |
||
| 139 | */ |
||
| 140 | protected $locked = true; |
||
| 141 | |||
| 142 | /** |
||
| 143 | * @var bool |
||
| 144 | */ |
||
| 145 | protected $isSegwit = false; |
||
| 146 | |||
| 147 | /** |
||
| 148 | * @var int |
||
| 149 | */ |
||
| 150 | protected $chainIndex; |
||
| 151 | |||
| 152 | /** |
||
| 153 | * @var int |
||
| 154 | */ |
||
| 155 | protected $changeIndex; |
||
| 156 | |||
| 157 | /** |
||
| 158 | * @var AddressReaderBase |
||
| 159 | */ |
||
| 160 | protected $addressReader; |
||
| 161 | |||
| 162 | protected $highPriorityFeePerKB; |
||
| 163 | protected $optimalFeePerKB; |
||
| 164 | protected $lowPriorityFeePerKB; |
||
| 165 | protected $feePerKBAge; |
||
| 166 | protected $allowedSignModes = [SignInfo::MODE_DONTSIGN, SignInfo::MODE_SIGN]; |
||
| 167 | |||
| 168 | /** |
||
| 169 | * @param BlocktrailSDKInterface $sdk SDK instance used to do requests |
||
| 170 | * @param string $identifier identifier of the wallet |
||
| 171 | * @param BIP32Key[] $primaryPublicKeys |
||
| 172 | * @param BIP32Key $backupPublicKey should be BIP32 master public key M/ |
||
| 173 | * @param BIP32Key[] $blocktrailPublicKeys |
||
| 174 | * @param int $keyIndex |
||
| 175 | * @param string $network |
||
| 176 | * @param bool $testnet |
||
| 177 | * @param bool $segwit |
||
| 178 | * @param string $checksum |
||
| 179 | * @throws BlocktrailSDKException |
||
| 180 | */ |
||
| 181 | 31 | public function __construct(BlocktrailSDKInterface $sdk, $identifier, array $primaryPublicKeys, $backupPublicKey, array $blocktrailPublicKeys, $keyIndex, $network, $testnet, $segwit, AddressReaderBase $addressReader, $checksum) { |
|
| 215 | |||
| 216 | /** |
||
| 217 | * @return AddressReaderBase |
||
| 218 | */ |
||
| 219 | 8 | public function getAddressReader() { |
|
| 222 | |||
| 223 | /** |
||
| 224 | * @param int|null $chainIndex |
||
| 225 | * @return WalletPath |
||
| 226 | * @throws BlocktrailSDKException |
||
| 227 | */ |
||
| 228 | 10 | protected function getWalletPath($chainIndex = null) { |
|
| 238 | |||
| 239 | /** |
||
| 240 | * @return bool |
||
| 241 | */ |
||
| 242 | 4 | public function isSegwit() { |
|
| 245 | |||
| 246 | /** |
||
| 247 | * return the wallet identifier |
||
| 248 | * |
||
| 249 | * @return string |
||
| 250 | */ |
||
| 251 | 3 | public function getIdentifier() { |
|
| 254 | |||
| 255 | /** |
||
| 256 | * Returns the wallets backup public key |
||
| 257 | * |
||
| 258 | * @return [xpub, path] |
||
|
|
|||
| 259 | */ |
||
| 260 | public function getBackupKey() { |
||
| 261 | return $this->backupPublicKey->tuple(); |
||
| 262 | } |
||
| 263 | |||
| 264 | /** |
||
| 265 | * return list of Blocktrail co-sign extended public keys |
||
| 266 | * |
||
| 267 | * @return array[] [ [xpub, path] ] |
||
| 268 | */ |
||
| 269 | public function getBlocktrailPublicKeys() { |
||
| 274 | |||
| 275 | /** |
||
| 276 | * check if wallet is locked |
||
| 277 | * |
||
| 278 | * @return bool |
||
| 279 | */ |
||
| 280 | public function isLocked() { |
||
| 281 | return $this->locked; |
||
| 282 | } |
||
| 283 | |||
| 284 | /** |
||
| 285 | * upgrade wallet to different blocktrail cosign key |
||
| 286 | * |
||
| 287 | * @param $keyIndex |
||
| 288 | * @return bool |
||
| 289 | * @throws \Exception |
||
| 290 | */ |
||
| 291 | 2 | public function upgradeKeyIndex($keyIndex) { |
|
| 318 | |||
| 319 | /** |
||
| 320 | * get a new BIP32 derivation for the next (unused) address |
||
| 321 | * by requesting it from the API |
||
| 322 | * |
||
| 323 | * @return string |
||
| 324 | * @param int|null $chainIndex |
||
| 325 | * @throws \Exception |
||
| 326 | */ |
||
| 327 | 10 | protected function getNewDerivation($chainIndex = null) { |
|
| 384 | |||
| 385 | /** |
||
| 386 | * @param string|BIP32Path $path |
||
| 387 | * @return BIP32Key|false |
||
| 388 | * @throws \Exception |
||
| 389 | * |
||
| 390 | * @TODO: hmm? |
||
| 391 | */ |
||
| 392 | 18 | protected function getParentPublicKey($path) { |
|
| 409 | |||
| 410 | /** |
||
| 411 | * get address for the specified path |
||
| 412 | * |
||
| 413 | * @param string|BIP32Path $path |
||
| 414 | * @return string |
||
| 415 | */ |
||
| 416 | 9 | public function getAddressByPath($path) { |
|
| 427 | |||
| 428 | /** |
||
| 429 | * @param string $path |
||
| 430 | * @return WalletScript |
||
| 431 | */ |
||
| 432 | 18 | public function getWalletScriptByPath($path) { |
|
| 444 | |||
| 445 | /** |
||
| 446 | * get address and redeemScript for specified path |
||
| 447 | * |
||
| 448 | * @param string $path |
||
| 449 | * @return array[string, ScriptInterface, ScriptInterface|null] [address, redeemScript, witnessScript] |
||
| 450 | */ |
||
| 451 | 17 | public function getRedeemScriptByPath($path) { |
|
| 458 | |||
| 459 | /** |
||
| 460 | * @param BIP32Key $key |
||
| 461 | * @param string|BIP32Path $path |
||
| 462 | * @return string |
||
| 463 | */ |
||
| 464 | protected function getAddressFromKey(BIP32Key $key, $path) { |
||
| 467 | |||
| 468 | /** |
||
| 469 | * @param BIP32Key $key |
||
| 470 | * @param string|BIP32Path $path |
||
| 471 | * @return WalletScript |
||
| 472 | * @throws \Exception |
||
| 473 | */ |
||
| 474 | 18 | protected function getWalletScriptFromKey(BIP32Key $key, $path) { |
|
| 502 | |||
| 503 | /** |
||
| 504 | * get the path (and redeemScript) to specified address |
||
| 505 | * |
||
| 506 | * @param string $address |
||
| 507 | * @return array |
||
| 508 | */ |
||
| 509 | public function getPathForAddress($address) { |
||
| 510 | $decoded = $this->addressReader->fromString($address); |
||
| 511 | if ($decoded instanceof CashAddress) { |
||
| 512 | $address = $decoded->getLegacyAddress(); |
||
| 513 | } |
||
| 514 | |||
| 515 | return $this->sdk->getPathForAddress($this->identifier, $address); |
||
| 516 | } |
||
| 517 | |||
| 518 | /** |
||
| 519 | * @param string|BIP32Path $path |
||
| 520 | * @return BIP32Key |
||
| 521 | * @throws \Exception |
||
| 522 | */ |
||
| 523 | 18 | public function getBlocktrailPublicKey($path) { |
|
| 534 | |||
| 535 | /** |
||
| 536 | * generate a new derived key and return the new path and address for it |
||
| 537 | * |
||
| 538 | * @param int|null $chainIndex |
||
| 539 | * @return string[] [path, address] |
||
| 540 | */ |
||
| 541 | 10 | public function getNewAddressPair($chainIndex = null) { |
|
| 547 | |||
| 548 | /** |
||
| 549 | * generate a new derived private key and return the new address for it |
||
| 550 | * |
||
| 551 | * @param int|null $chainIndex |
||
| 552 | * @return string |
||
| 553 | */ |
||
| 554 | 1 | public function getNewAddress($chainIndex = null) { |
|
| 557 | |||
| 558 | /** |
||
| 559 | * generate a new derived private key and return the new address for it |
||
| 560 | * |
||
| 561 | * @return string |
||
| 562 | */ |
||
| 563 | public function getNewChangeAddress() { |
||
| 564 | return $this->getNewAddressPair($this->changeIndex)[1]; |
||
| 565 | } |
||
| 566 | |||
| 567 | /** |
||
| 568 | * get the balance for the wallet |
||
| 569 | * |
||
| 570 | * @return int[] [confirmed, unconfirmed] |
||
| 571 | */ |
||
| 572 | public function getBalance() { |
||
| 573 | $balanceInfo = $this->sdk->getWalletBalance($this->identifier); |
||
| 574 | |||
| 575 | return [$balanceInfo['confirmed'], $balanceInfo['unconfirmed']]; |
||
| 576 | } |
||
| 577 | |||
| 578 | /** |
||
| 579 | * create, sign and send a transaction |
||
| 580 | * |
||
| 581 | * @param array $outputs [address => value, ] or [[address, value], ] or [['address' => address, 'value' => value], ] coins to send |
||
| 582 | * value should be INT |
||
| 583 | * @param string $changeAddress change address to use (autogenerated if NULL) |
||
| 584 | * @param bool $allowZeroConf |
||
| 585 | * @param bool $randomizeChangeIdx randomize the location of the change (for increased privacy / anonimity) |
||
| 586 | * @param string $feeStrategy |
||
| 587 | * @param null|int $forceFee set a fixed fee instead of automatically calculating the correct fee, not recommended! |
||
| 588 | * @param bool $apiCheckFee let the API apply sanity checks to the fee |
||
| 589 | * @return string the txid / transaction hash |
||
| 590 | * @throws \Exception |
||
| 591 | */ |
||
| 592 | 7 | public function pay(array $outputs, $changeAddress = null, $allowZeroConf = false, $randomizeChangeIdx = true, $feeStrategy = self::FEE_STRATEGY_OPTIMAL, $forceFee = null, $apiCheckFee = true) { |
|
| 620 | |||
| 621 | /** |
||
| 622 | * determine max spendable from wallet after fees |
||
| 623 | * |
||
| 624 | * @param bool $allowZeroConf |
||
| 625 | * @param string $feeStrategy |
||
| 626 | * @param null|int $forceFee set a fixed fee instead of automatically calculating the correct fee, not recommended! |
||
| 627 | * @param int $outputCnt |
||
| 628 | * @return string |
||
| 629 | * @throws BlocktrailSDKException |
||
| 630 | */ |
||
| 631 | public function getMaxSpendable($allowZeroConf = false, $feeStrategy = self::FEE_STRATEGY_OPTIMAL, $forceFee = null, $outputCnt = 1) { |
||
| 634 | |||
| 635 | /** |
||
| 636 | * parse outputs into normalized struct |
||
| 637 | * |
||
| 638 | * @param array $outputs [address => value, ] or [[address, value], ] or [['address' => address, 'value' => value], ] |
||
| 639 | * @return array [['address' => address, 'value' => value], ] |
||
| 640 | */ |
||
| 641 | 1 | public static function normalizeOutputsStruct(array $outputs) { |
|
| 669 | |||
| 670 | /** |
||
| 671 | * 'fund' the txBuilder with UTXOs (modified in place) |
||
| 672 | * |
||
| 673 | * @param TransactionBuilder $txBuilder |
||
| 674 | * @param bool|true $lockUTXOs |
||
| 675 | * @param bool|false $allowZeroConf |
||
| 676 | * @param null|int $forceFee |
||
| 677 | * @return TransactionBuilder |
||
| 678 | */ |
||
| 679 | 8 | public function coinSelectionForTxBuilder(TransactionBuilder $txBuilder, $lockUTXOs = true, $allowZeroConf = false, $forceFee = null) { |
|
| 708 | |||
| 709 | /** |
||
| 710 | * build inputs and outputs lists for TransactionBuilder |
||
| 711 | * |
||
| 712 | * @param TransactionBuilder $txBuilder |
||
| 713 | * @return [TransactionInterface, SignInfo[]] |
||
| 714 | * @throws \Exception |
||
| 715 | */ |
||
| 716 | 8 | public function buildTx(TransactionBuilder $txBuilder) { |
|
| 717 | 8 | $send = $txBuilder->getOutputs(); |
|
| 718 | 8 | $utxos = $txBuilder->getUtxos(); |
|
| 719 | 8 | $signInfo = []; |
|
| 720 | |||
| 721 | 8 | $txb = new TxBuilder(); |
|
| 722 | |||
| 723 | 8 | foreach ($utxos as $utxo) { |
|
| 724 | 8 | if (!$utxo->address || !$utxo->value || !$utxo->scriptPubKey) { |
|
| 725 | $tx = $this->sdk->transaction($utxo->hash); |
||
| 726 | |||
| 727 | if (!$tx || !isset($tx['outputs'][$utxo->index])) { |
||
| 728 | throw new \Exception("Invalid output [{$utxo->hash}][{$utxo->index}]"); |
||
| 729 | } |
||
| 730 | |||
| 731 | $output = $tx['outputs'][$utxo->index]; |
||
| 732 | |||
| 733 | if (!$utxo->address) { |
||
| 734 | $utxo->address = $this->addressReader->fromString($output['address']); |
||
| 735 | } |
||
| 736 | if (!$utxo->value) { |
||
| 737 | $utxo->value = $output['value']; |
||
| 738 | } |
||
| 739 | if (!$utxo->scriptPubKey) { |
||
| 740 | $utxo->scriptPubKey = ScriptFactory::fromHex($output['script_hex']); |
||
| 741 | } |
||
| 742 | } |
||
| 743 | |||
| 744 | 8 | if (SignInfo::MODE_SIGN === $utxo->signMode) { |
|
| 745 | 8 | if (!$utxo->path) { |
|
| 746 | $utxo->path = $this->getPathForAddress($utxo->address->getAddress()); |
||
| 747 | } |
||
| 748 | |||
| 749 | 8 | if (!$utxo->redeemScript || !$utxo->witnessScript) { |
|
| 750 | 7 | list(, $redeemScript, $witnessScript) = $this->getRedeemScriptByPath($utxo->path); |
|
| 751 | 7 | $utxo->redeemScript = $redeemScript; |
|
| 752 | 7 | $utxo->witnessScript = $witnessScript; |
|
| 753 | } |
||
| 754 | } |
||
| 755 | |||
| 756 | 8 | $signInfo[] = $utxo->getSignInfo(); |
|
| 757 | } |
||
| 758 | |||
| 759 | 8 | $utxoSum = array_sum(array_map(function (UTXO $utxo) { |
|
| 760 | 8 | return $utxo->value; |
|
| 761 | 8 | }, $utxos)); |
|
| 762 | 8 | if ($utxoSum < array_sum(array_column($send, 'value'))) { |
|
| 763 | throw new \Exception("Atempting to spend more than sum of UTXOs"); |
||
| 764 | } |
||
| 765 | |||
| 766 | 8 | list($fee, $change) = $this->determineFeeAndChange($txBuilder, $this->getHighPriorityFeePerKB(), $this->getOptimalFeePerKB(), $this->getLowPriorityFeePerKB()); |
|
| 767 | |||
| 768 | 8 | if ($txBuilder->getValidateFee() !== null) { |
|
| 769 | // sanity check to make sure the API isn't giving us crappy data |
||
| 770 | 7 | if (abs($txBuilder->getValidateFee() - $fee) > (Wallet::BASE_FEE * 5)) { |
|
| 771 | throw new \Exception("the fee suggested by the coin selection ({$txBuilder->getValidateFee()}) seems incorrect ({$fee})"); |
||
| 772 | } |
||
| 773 | } |
||
| 774 | |||
| 775 | 8 | if ($change > 0) { |
|
| 776 | 8 | $send[] = [ |
|
| 777 | 8 | 'address' => $txBuilder->getChangeAddress() ?: $this->getNewChangeAddress(), |
|
| 778 | 8 | 'value' => $change |
|
| 779 | ]; |
||
| 780 | } |
||
| 781 | |||
| 782 | 8 | foreach ($utxos as $utxo) { |
|
| 783 | 8 | $txb->spendOutPoint(new OutPoint(Buffer::hex($utxo->hash), $utxo->index)); |
|
| 784 | } |
||
| 785 | |||
| 786 | // outputs should be randomized to make the change harder to detect |
||
| 787 | 8 | if ($txBuilder->shouldRandomizeChangeOuput()) { |
|
| 788 | 3 | $this->sdk->shuffle($send); |
|
| 789 | } |
||
| 790 | |||
| 791 | 8 | foreach ($send as $out) { |
|
| 792 | 8 | assert(isset($out['value'])); |
|
| 793 | |||
| 794 | 8 | if (isset($out['scriptPubKey'])) { |
|
| 795 | 8 | $txb->output($out['value'], $out['scriptPubKey']); |
|
| 796 | 8 | } elseif (isset($out['address'])) { |
|
| 797 | 8 | $txb->output($out['value'], $this->addressReader->fromString($out['address'])->getScriptPubKey()); |
|
| 798 | } else { |
||
| 799 | 8 | throw new \Exception(); |
|
| 800 | } |
||
| 801 | } |
||
| 802 | |||
| 803 | 8 | return [$txb->get(), $signInfo]; |
|
| 804 | } |
||
| 805 | |||
| 806 | 8 | public function determineFeeAndChange(TransactionBuilder $txBuilder, $highPriorityFeePerKB, $optimalFeePerKB, $lowPriorityFeePerKB) { |
|
| 807 | 8 | $send = (new OutputsNormalizer($this->addressReader))->normalize($txBuilder->getOutputs()); |
|
| 808 | 8 | $utxos = $txBuilder->getUtxos(); |
|
| 809 | |||
| 810 | 8 | $fee = $txBuilder->getFee(); |
|
| 811 | 8 | $change = null; |
|
| 812 | |||
| 813 | // if the fee is fixed we just need to calculate the change |
||
| 814 | 8 | if ($fee !== null) { |
|
| 815 | 1 | $change = $this->determineChange($utxos, $send, $fee); |
|
| 816 | |||
| 817 | // if change is not dust we need to add a change output |
||
| 818 | 1 | if ($change > Blocktrail::DUST) { |
|
| 819 | 1 | $send[] = ['address' => 'change', 'value' => $change]; |
|
| 820 | } else { |
||
| 821 | // if change is dust we add it to the fee |
||
| 822 | $fee += $change; |
||
| 823 | $change = 0; |
||
| 824 | } |
||
| 825 | |||
| 826 | 1 | return [$fee, $change]; |
|
| 827 | } else { |
||
| 828 | 7 | $fee = $this->determineFee($utxos, $send, $txBuilder->getFeeStrategy(), $highPriorityFeePerKB, $optimalFeePerKB, $lowPriorityFeePerKB); |
|
| 829 | |||
| 830 | 7 | $change = $this->determineChange($utxos, $send, $fee); |
|
| 831 | |||
| 832 | 7 | if ($change > 0) { |
|
| 833 | 7 | $changeIdx = count($send); |
|
| 834 | // set dummy change output |
||
| 835 | 7 | $send[$changeIdx] = ['address' => 'change', 'value' => $change]; |
|
| 836 | |||
| 837 | // recaculate fee now that we know that we have a change output |
||
| 838 | 7 | $fee2 = $this->determineFee($utxos, $send, $txBuilder->getFeeStrategy(), $highPriorityFeePerKB, $optimalFeePerKB, $lowPriorityFeePerKB); |
|
| 839 | |||
| 840 | // unset dummy change output |
||
| 841 | 7 | unset($send[$changeIdx]); |
|
| 842 | |||
| 843 | // if adding the change output made the fee bump up and the change is smaller than the fee |
||
| 844 | // then we're not doing change |
||
| 845 | 7 | if ($fee2 > $fee && $fee2 > $change) { |
|
| 846 | $change = 0; |
||
| 847 | } else { |
||
| 848 | 7 | $change = $this->determineChange($utxos, $send, $fee2); |
|
| 849 | |||
| 850 | // if change is not dust we need to add a change output |
||
| 851 | 7 | if ($change > Blocktrail::DUST) { |
|
| 852 | 7 | $send[$changeIdx] = ['address' => 'change', 'value' => $change]; |
|
| 853 | } else { |
||
| 854 | // if change is dust we do nothing (implicitly it's added to the fee) |
||
| 855 | $change = 0; |
||
| 856 | } |
||
| 857 | } |
||
| 858 | } |
||
| 859 | |||
| 860 | |||
| 861 | 7 | $fee = $this->determineFee($utxos, $send, $txBuilder->getFeeStrategy(), $highPriorityFeePerKB, $optimalFeePerKB, $lowPriorityFeePerKB); |
|
| 862 | |||
| 863 | 7 | return [$fee, $change]; |
|
| 864 | } |
||
| 865 | } |
||
| 866 | |||
| 867 | /** |
||
| 868 | * create, sign and send transction based on TransactionBuilder |
||
| 869 | * |
||
| 870 | * @param TransactionBuilder $txBuilder |
||
| 871 | * @param bool $apiCheckFee let the API check if the fee is correct |
||
| 872 | * @return string |
||
| 873 | * @throws \Exception |
||
| 874 | */ |
||
| 875 | 6 | public function sendTx(TransactionBuilder $txBuilder, $apiCheckFee = true) { |
|
| 880 | |||
| 881 | /** |
||
| 882 | * !! INTERNAL METHOD, public for testing purposes !! |
||
| 883 | * create, sign and send transction based on inputs and outputs |
||
| 884 | * |
||
| 885 | * @param Transaction $tx |
||
| 886 | * @param SignInfo[] $signInfo |
||
| 887 | * @param bool $apiCheckFee let the API check if the fee is correct |
||
| 888 | * @return string |
||
| 889 | * @throws \Exception |
||
| 890 | * @internal |
||
| 891 | */ |
||
| 892 | 6 | public function _sendTx(Transaction $tx, array $signInfo, $apiCheckFee = true) { |
|
| 893 | 6 | if ($this->locked) { |
|
| 894 | throw new \Exception("Wallet needs to be unlocked to pay"); |
||
| 895 | } |
||
| 896 | |||
| 897 | 6 | assert(Util::all(function ($signInfo) { |
|
| 898 | 6 | return $signInfo instanceof SignInfo; |
|
| 899 | 6 | }, $signInfo), '$signInfo should be SignInfo[]'); |
|
| 900 | |||
| 901 | // sign the transaction with our keys |
||
| 902 | 6 | $signed = $this->signTransaction($tx, $signInfo); |
|
| 903 | |||
| 904 | $txs = [ |
||
| 905 | 6 | 'signed_transaction' => $signed->getHex(), |
|
| 906 | 6 | 'base_transaction' => $signed->getBaseSerialization()->getHex(), |
|
| 907 | ]; |
||
| 908 | |||
| 909 | // send the transaction |
||
| 910 | 6 | return $this->sendTransaction($txs, array_map(function (SignInfo $r) { |
|
| 911 | 6 | return (string)$r->path; |
|
| 912 | 6 | }, $signInfo), $apiCheckFee); |
|
| 913 | } |
||
| 914 | |||
| 915 | /** |
||
| 916 | * only supports estimating fee for 2of3 multsig UTXOs and P2PKH/P2SH outputs |
||
| 917 | * |
||
| 918 | * @todo: mark this as deprecated, insist on the utxo's or qualified scripts. |
||
| 919 | * @param int $utxoCnt number of unspent inputs in transaction |
||
| 920 | * @param int $outputCnt number of outputs in transaction |
||
| 921 | * @return float |
||
| 922 | * @access public reminder that people might use this! |
||
| 923 | */ |
||
| 924 | public static function estimateFee($utxoCnt, $outputCnt) { |
||
| 925 | $size = self::estimateSize(self::estimateSizeUTXOs($utxoCnt), self::estimateSizeOutputs($outputCnt)); |
||
| 926 | |||
| 927 | return self::baseFeeForSize($size); |
||
| 928 | } |
||
| 929 | |||
| 930 | /** |
||
| 931 | * @param int $size size in bytes |
||
| 932 | * @return int fee in satoshi |
||
| 933 | */ |
||
| 934 | public static function baseFeeForSize($size) { |
||
| 935 | $sizeKB = (int)ceil($size / 1000); |
||
| 936 | |||
| 937 | return $sizeKB * self::BASE_FEE; |
||
| 938 | } |
||
| 939 | |||
| 940 | /** |
||
| 941 | * @todo: variable varint |
||
| 942 | * @todo: deprecate |
||
| 943 | * @param int $txinSize |
||
| 944 | * @param int $txoutSize |
||
| 945 | * @return float |
||
| 946 | */ |
||
| 947 | public static function estimateSize($txinSize, $txoutSize) { |
||
| 948 | return 4 + 4 + $txinSize + 4 + $txoutSize + 4; // version + txinVarInt + txin + txoutVarInt + txout + locktime |
||
| 949 | } |
||
| 950 | |||
| 951 | /** |
||
| 952 | * only supports estimating size for P2PKH/P2SH outputs |
||
| 953 | * |
||
| 954 | * @param int $outputCnt number of outputs in transaction |
||
| 955 | * @return float |
||
| 956 | */ |
||
| 957 | public static function estimateSizeOutputs($outputCnt) { |
||
| 958 | return ($outputCnt * 34); |
||
| 959 | } |
||
| 960 | |||
| 961 | /** |
||
| 962 | * only supports estimating size for 2of3 multsig UTXOs |
||
| 963 | * |
||
| 964 | * @param int $utxoCnt number of unspent inputs in transaction |
||
| 965 | * @return float |
||
| 966 | */ |
||
| 967 | public static function estimateSizeUTXOs($utxoCnt) { |
||
| 968 | $txinSize = 0; |
||
| 969 | |||
| 970 | for ($i=0; $i<$utxoCnt; $i++) { |
||
| 971 | // @TODO: proper size calculation, we only do multisig right now so it's hardcoded and then we guess the size ... |
||
| 972 | $multisig = "2of3"; |
||
| 973 | |||
| 974 | if ($multisig) { |
||
| 975 | $sigCnt = 2; |
||
| 976 | $msig = explode("of", $multisig); |
||
| 977 | if (count($msig) == 2 && is_numeric($msig[0])) { |
||
| 978 | $sigCnt = $msig[0]; |
||
| 979 | } |
||
| 980 | |||
| 981 | $txinSize += array_sum([ |
||
| 982 | 32, // txhash |
||
| 983 | 4, // idx |
||
| 984 | 3, // scriptVarInt[>=253] |
||
| 985 | ((1 + 72) * $sigCnt), // (OP_PUSHDATA[<75] + 72) * sigCnt |
||
| 986 | (2 + 105) + // OP_PUSHDATA[>=75] + script |
||
| 987 | 1, // OP_0 |
||
| 988 | 4, // sequence |
||
| 989 | ]); |
||
| 990 | } else { |
||
| 991 | $txinSize += array_sum([ |
||
| 992 | 32, // txhash |
||
| 993 | 4, // idx |
||
| 994 | 73, // sig |
||
| 995 | 34, // script |
||
| 996 | 4, // sequence |
||
| 997 | ]); |
||
| 998 | } |
||
| 999 | } |
||
| 1000 | |||
| 1001 | return $txinSize; |
||
| 1002 | } |
||
| 1003 | |||
| 1004 | /** |
||
| 1005 | * determine how much fee is required based on the inputs and outputs |
||
| 1006 | * this is an estimation, not a proper 100% correct calculation |
||
| 1007 | * |
||
| 1008 | * @param UTXO[] $utxos |
||
| 1009 | * @param array[] $outputs |
||
| 1010 | * @param $feeStrategy |
||
| 1011 | * @param $highPriorityFeePerKB |
||
| 1012 | * @param $optimalFeePerKB |
||
| 1013 | * @param $lowPriorityFeePerKB |
||
| 1014 | * @return int |
||
| 1015 | * @throws BlocktrailSDKException |
||
| 1016 | */ |
||
| 1017 | 7 | protected function determineFee($utxos, $outputs, $feeStrategy, $highPriorityFeePerKB, $optimalFeePerKB, $lowPriorityFeePerKB) { |
|
| 1018 | |||
| 1019 | 7 | $size = SizeEstimation::estimateVsize($utxos, $outputs); |
|
| 1020 | |||
| 1021 | switch ($feeStrategy) { |
||
| 1022 | 7 | case self::FEE_STRATEGY_BASE_FEE: |
|
| 1023 | return self::baseFeeForSize($size); |
||
| 1024 | |||
| 1025 | 7 | case self::FEE_STRATEGY_HIGH_PRIORITY: |
|
| 1026 | return (int)round(($size / 1000) * $highPriorityFeePerKB); |
||
| 1027 | |||
| 1028 | 7 | case self::FEE_STRATEGY_OPTIMAL: |
|
| 1029 | 6 | return (int)round(($size / 1000) * $optimalFeePerKB); |
|
| 1030 | |||
| 1031 | 1 | case self::FEE_STRATEGY_LOW_PRIORITY: |
|
| 1032 | 1 | return (int)round(($size / 1000) * $lowPriorityFeePerKB); |
|
| 1033 | |||
| 1034 | case self::FEE_STRATEGY_FORCE_FEE: |
||
| 1035 | throw new BlocktrailSDKException("Can't determine when for force_fee"); |
||
| 1036 | |||
| 1037 | default: |
||
| 1038 | throw new BlocktrailSDKException("Unknown feeStrategy [{$feeStrategy}]"); |
||
| 1039 | } |
||
| 1040 | } |
||
| 1041 | |||
| 1042 | /** |
||
| 1043 | * determine how much change is left over based on the inputs and outputs and the fee |
||
| 1044 | * |
||
| 1045 | * @param UTXO[] $utxos |
||
| 1046 | * @param array[] $outputs |
||
| 1047 | * @param int $fee |
||
| 1048 | * @return int |
||
| 1049 | */ |
||
| 1050 | protected function determineChange($utxos, $outputs, $fee) { |
||
| 1058 | |||
| 1059 | /** |
||
| 1060 | * sign a raw transaction with the private keys that we have |
||
| 1061 | * |
||
| 1062 | * @param Transaction $tx |
||
| 1063 | * @param SignInfo[] $signInfo |
||
| 1064 | * @return TransactionInterface |
||
| 1065 | * @throws \Exception |
||
| 1066 | */ |
||
| 1067 | 6 | protected function signTransaction(Transaction $tx, array $signInfo) { |
|
| 1099 | |||
| 1100 | /** |
||
| 1101 | * send the transaction using the API |
||
| 1102 | * |
||
| 1103 | * @param string|array $signed |
||
| 1104 | * @param string[] $paths |
||
| 1105 | * @param bool $checkFee |
||
| 1106 | * @return string the complete raw transaction |
||
| 1107 | * @throws \Exception |
||
| 1108 | */ |
||
| 1109 | 6 | protected function sendTransaction($signed, $paths, $checkFee = false) { |
|
| 1112 | |||
| 1113 | /** |
||
| 1114 | * @param \array[] $outputs |
||
| 1115 | * @param bool $lockUTXO |
||
| 1116 | * @param bool $allowZeroConf |
||
| 1117 | * @param int|null|string $feeStrategy |
||
| 1118 | * @param null $forceFee |
||
| 1119 | * @return array |
||
| 1120 | */ |
||
| 1121 | 8 | public function coinSelection($outputs, $lockUTXO = true, $allowZeroConf = false, $feeStrategy = self::FEE_STRATEGY_OPTIMAL, $forceFee = null) { |
|
| 1139 | |||
| 1140 | 8 | public function getHighPriorityFeePerKB() { |
|
| 1141 | 8 | if (!$this->highPriorityFeePerKB || $this->feePerKBAge < time() - 60) { |
|
| 1142 | $this->updateFeePerKB(); |
||
| 1143 | } |
||
| 1144 | |||
| 1145 | 8 | return $this->highPriorityFeePerKB; |
|
| 1146 | } |
||
| 1147 | |||
| 1148 | 8 | public function getOptimalFeePerKB() { |
|
| 1155 | |||
| 1156 | 8 | public function getLowPriorityFeePerKB() { |
|
| 1163 | |||
| 1164 | public function updateFeePerKB() { |
||
| 1165 | $result = $this->sdk->feePerKB(); |
||
| 1166 | |||
| 1167 | $this->highPriorityFeePerKB = $result[self::FEE_STRATEGY_HIGH_PRIORITY]; |
||
| 1168 | $this->optimalFeePerKB = $result[self::FEE_STRATEGY_OPTIMAL]; |
||
| 1169 | $this->lowPriorityFeePerKB = $result[self::FEE_STRATEGY_LOW_PRIORITY]; |
||
| 1170 | |||
| 1171 | $this->feePerKBAge = time(); |
||
| 1172 | } |
||
| 1173 | |||
| 1174 | /** |
||
| 1175 | * delete the wallet |
||
| 1176 | * |
||
| 1177 | * @param bool $force ignore warnings (such as non-zero balance) |
||
| 1178 | * @return mixed |
||
| 1179 | * @throws \Exception |
||
| 1180 | */ |
||
| 1181 | public function deleteWallet($force = false) { |
||
| 1182 | if ($this->locked) { |
||
| 1183 | throw new \Exception("Wallet needs to be unlocked to delete wallet"); |
||
| 1184 | } |
||
| 1185 | |||
| 1186 | list($checksumAddress, $signature) = $this->createChecksumVerificationSignature(); |
||
| 1187 | return $this->sdk->deleteWallet($this->identifier, $checksumAddress, $signature, $force)['deleted']; |
||
| 1188 | } |
||
| 1189 | |||
| 1190 | /** |
||
| 1191 | * create checksum to verify ownership of the master primary key |
||
| 1192 | * |
||
| 1193 | * @return string[] [address, signature] |
||
| 1194 | */ |
||
| 1195 | protected function createChecksumVerificationSignature() { |
||
| 1196 | $privKey = $this->primaryPrivateKey->key(); |
||
| 1197 | |||
| 1198 | $pubKey = $this->primaryPrivateKey->publicKey(); |
||
| 1199 | $address = $pubKey->getAddress()->getAddress(); |
||
| 1200 | |||
| 1201 | $signer = new MessageSigner(Bitcoin::getEcAdapter()); |
||
| 1202 | $signed = $signer->sign($address, $privKey->getPrivateKey()); |
||
| 1203 | |||
| 1204 | return [$address, base64_encode($signed->getCompactSignature()->getBuffer()->getBinary())]; |
||
| 1205 | } |
||
| 1206 | |||
| 1207 | /** |
||
| 1208 | * setup a webhook for our wallet |
||
| 1209 | * |
||
| 1210 | * @param string $url URL to receive webhook events |
||
| 1211 | * @param string $identifier identifier for the webhook, defaults to WALLET-{$this->identifier} |
||
| 1212 | * @return array |
||
| 1213 | */ |
||
| 1214 | 2 | public function setupWebhook($url, $identifier = null) { |
|
| 1218 | |||
| 1219 | /** |
||
| 1220 | * @param string $identifier identifier for the webhook, defaults to WALLET-{$this->identifier} |
||
| 1221 | * @return mixed |
||
| 1222 | */ |
||
| 1223 | 2 | public function deleteWebhook($identifier = null) { |
|
| 1227 | |||
| 1228 | /** |
||
| 1229 | * lock a specific unspent output |
||
| 1230 | * |
||
| 1231 | * @param $txHash |
||
| 1232 | * @param $txIdx |
||
| 1233 | * @param int $ttl |
||
| 1234 | * @return bool |
||
| 1235 | */ |
||
| 1236 | public function lockUTXO($txHash, $txIdx, $ttl = 3) { |
||
| 1239 | |||
| 1240 | /** |
||
| 1241 | * unlock a specific unspent output |
||
| 1242 | * |
||
| 1243 | * @param $txHash |
||
| 1244 | * @param $txIdx |
||
| 1245 | * @return bool |
||
| 1246 | */ |
||
| 1247 | public function unlockUTXO($txHash, $txIdx) { |
||
| 1250 | |||
| 1251 | /** |
||
| 1252 | * get all transactions for the wallet (paginated) |
||
| 1253 | * |
||
| 1254 | * @param integer $page pagination: page number |
||
| 1255 | * @param integer $limit pagination: records per page (max 500) |
||
| 1256 | * @param string $sortDir pagination: sort direction (asc|desc) |
||
| 1257 | * @return array associative array containing the response |
||
| 1258 | */ |
||
| 1259 | 1 | public function transactions($page = 1, $limit = 20, $sortDir = 'asc') { |
|
| 1262 | |||
| 1263 | /** |
||
| 1264 | * get all addresses for the wallet (paginated) |
||
| 1265 | * |
||
| 1266 | * @param integer $page pagination: page number |
||
| 1267 | * @param integer $limit pagination: records per page (max 500) |
||
| 1268 | * @param string $sortDir pagination: sort direction (asc|desc) |
||
| 1269 | * @return array associative array containing the response |
||
| 1270 | */ |
||
| 1271 | public function addresses($page = 1, $limit = 20, $sortDir = 'asc') { |
||
| 1274 | |||
| 1275 | /** |
||
| 1276 | * get all UTXOs for the wallet (paginated) |
||
| 1277 | * |
||
| 1278 | * @param integer $page pagination: page number |
||
| 1279 | * @param integer $limit pagination: records per page (max 500) |
||
| 1280 | * @param string $sortDir pagination: sort direction (asc|desc) |
||
| 1281 | * @param boolean $zeroconf include zero confirmation transactions |
||
| 1282 | * @return array associative array containing the response |
||
| 1283 | */ |
||
| 1284 | public function utxos($page = 1, $limit = 20, $sortDir = 'asc', $zeroconf = true) { |
||
| 1287 | } |
||
| 1288 |
This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.