chia-blockchain/src/wallet/wallet.py

438 lines
16 KiB
Python
Raw Normal View History

2020-04-28 04:42:08 +03:00
import time
from typing import Dict, Optional, List, Tuple, Set, Any
2020-02-12 04:01:39 +03:00
import clvm
2020-02-12 00:00:41 +03:00
import logging
from src.types.BLSSignature import BLSSignature
from src.types.coin import Coin
from src.types.coin_solution import CoinSolution
from src.types.program import Program
from src.types.spend_bundle import SpendBundle
2020-02-12 04:01:39 +03:00
from src.types.sized_bytes import bytes32
2020-02-13 22:57:40 +03:00
from src.util.condition_tools import (
conditions_for_solution,
2020-04-21 16:55:59 +03:00
conditions_dict_for_solution,
2020-02-13 22:57:40 +03:00
conditions_by_opcode,
hash_key_pairs_for_conditions_dict,
)
2020-04-28 04:42:08 +03:00
from src.util.ints import uint64, uint32
2020-02-12 04:01:39 +03:00
from src.wallet.BLSPrivateKey import BLSPrivateKey
from src.wallet.puzzles.p2_conditions import puzzle_for_conditions
from src.wallet.puzzles.p2_delegated_puzzle import puzzle_for_pk
2020-02-13 22:57:40 +03:00
from src.wallet.puzzles.puzzle_utils import (
make_assert_my_coin_id_condition,
make_assert_time_exceeds_condition,
make_assert_coin_consumed_condition,
make_create_coin_condition,
2020-04-20 08:10:19 +03:00
make_assert_fee_condition,
)
2020-04-28 04:42:08 +03:00
from src.wallet.transaction_record import TransactionRecord
2020-03-19 11:26:51 +03:00
from src.wallet.wallet_coin_record import WalletCoinRecord
from src.wallet.wallet_info import WalletInfo
2020-02-24 20:16:47 +03:00
2020-02-12 00:00:41 +03:00
class Wallet:
wallet_state_manager: Any
2020-02-13 22:57:40 +03:00
log: logging.Logger
2020-03-19 11:26:51 +03:00
wallet_info: WalletInfo
2020-02-13 23:59:03 +03:00
2020-02-13 22:57:40 +03:00
@staticmethod
2020-02-24 21:41:54 +03:00
async def create(
wallet_state_manager: Any, info: WalletInfo, name: str = None,
2020-02-24 21:41:54 +03:00
):
2020-02-13 22:57:40 +03:00
self = Wallet()
2020-04-15 03:44:17 +03:00
2020-02-12 00:00:41 +03:00
if name:
self.log = logging.getLogger(name)
else:
self.log = logging.getLogger(__name__)
2020-02-24 20:16:47 +03:00
self.wallet_state_manager = wallet_state_manager
2020-02-13 23:59:03 +03:00
2020-03-19 11:26:51 +03:00
self.wallet_info = info
2020-02-13 22:57:40 +03:00
return self
2020-02-12 04:01:39 +03:00
2020-02-13 23:59:03 +03:00
async def get_confirmed_balance(self) -> uint64:
2020-03-19 22:11:58 +03:00
return await self.wallet_state_manager.get_confirmed_balance_for_wallet(
self.wallet_info.id
)
2020-02-13 22:57:40 +03:00
2020-02-13 23:59:03 +03:00
async def get_unconfirmed_balance(self) -> uint64:
2020-03-19 22:11:58 +03:00
return await self.wallet_state_manager.get_unconfirmed_balance(
self.wallet_info.id
)
2020-02-13 23:59:03 +03:00
def puzzle_for_pk(self, pubkey: bytes) -> Program:
2020-02-12 04:01:39 +03:00
return puzzle_for_pk(pubkey)
2020-04-10 17:53:31 +03:00
async def get_new_puzzle(self) -> Program:
return puzzle_for_pk(
bytes(
self.wallet_state_manager.get_unused_derivation_record(
self.wallet_info.id
).pubkey
)
)
async def get_new_puzzlehash(self) -> bytes32:
return (
await self.wallet_state_manager.get_unused_derivation_record(
self.wallet_info.id
)
).puzzle_hash
2020-02-12 04:01:39 +03:00
2020-04-20 08:10:19 +03:00
def make_solution(
self, primaries=None, min_time=0, me=None, consumed=None, fee=None
):
2020-03-06 02:53:36 +03:00
condition_list = []
2020-02-13 22:57:40 +03:00
if primaries:
for primary in primaries:
2020-03-06 02:53:36 +03:00
condition_list.append(
2020-02-13 22:57:40 +03:00
make_create_coin_condition(primary["puzzlehash"], primary["amount"])
)
if consumed:
for coin in consumed:
2020-03-06 02:53:36 +03:00
condition_list.append(make_assert_coin_consumed_condition(coin))
2020-02-12 04:01:39 +03:00
if min_time > 0:
2020-03-06 02:53:36 +03:00
condition_list.append(make_assert_time_exceeds_condition(min_time))
2020-02-12 04:01:39 +03:00
if me:
2020-03-06 02:53:36 +03:00
condition_list.append(make_assert_my_coin_id_condition(me["id"]))
2020-04-20 08:08:16 +03:00
if fee:
condition_list.append(make_assert_fee_condition(fee))
2020-03-06 02:53:36 +03:00
return clvm.to_sexp_f([puzzle_for_conditions(condition_list), []])
2020-02-12 04:01:39 +03:00
2020-04-22 09:56:48 +03:00
async def select_coins(
self, amount, exclude: List[Coin] = None
) -> Optional[Set[Coin]]:
2020-03-19 11:26:51 +03:00
""" Returns a set of coins that can be used for generating a new transaction. """
async with self.wallet_state_manager.lock:
2020-04-22 08:59:48 +03:00
if exclude is None:
exclude = []
spendable_am = await self.wallet_state_manager.get_unconfirmed_spendable_for_wallet(
self.wallet_info.id
2020-04-01 07:02:07 +03:00
)
2020-03-19 11:26:51 +03:00
if amount > spendable_am:
self.log.warning(
f"Can't select amount higher than our spendable balance {amount}, spendable {spendable_am}"
)
return None
2020-03-19 11:26:51 +03:00
self.log.info(f"About to select coins for amount {amount}")
unspent: List[WalletCoinRecord] = list(
await self.wallet_state_manager.get_spendable_coins_for_wallet(
self.wallet_info.id
)
2020-04-02 20:33:38 +03:00
)
sum = 0
used_coins: Set = set()
# Use older coins first
unspent.sort(key=lambda r: r.confirmed_block_index)
# Try to use coins from the store, if there isn't enough of "unused"
# coins use change coins that are not confirmed yet
unconfirmed_removals: Dict[
bytes32, Coin
] = await self.wallet_state_manager.unconfirmed_removals_for_wallet(
2020-03-28 00:03:48 +03:00
self.wallet_info.id
)
for coinrecord in unspent:
2020-04-23 16:40:25 +03:00
if sum >= amount and len(used_coins) > 0:
2020-03-19 11:26:51 +03:00
break
if coinrecord.coin.name() in unconfirmed_removals:
2020-03-19 11:26:51 +03:00
continue
2020-04-22 08:59:48 +03:00
if coinrecord.coin in exclude:
continue
sum += coinrecord.coin.amount
used_coins.add(coinrecord.coin)
self.log.info(
f"Selected coin: {coinrecord.coin.name()} at height {coinrecord.confirmed_block_index}!"
)
2020-03-28 00:03:48 +03:00
# This happens when we couldn't use one of the coins because it's already used
# but unconfirmed, and we are waiting for the change. (unconfirmed_additions)
unconfirmed_additions = None
if sum < amount:
raise ValueError(
"Can't make this transaction at the moment. Waiting for the change from the previous transaction."
)
unconfirmed_additions = await self.wallet_state_manager.unconfirmed_additions_for_wallet(
self.wallet_info.id
)
for coin in unconfirmed_additions.values():
if sum > amount:
break
if coin.name() in unconfirmed_removals:
continue
sum += coin.amount
used_coins.add(coin)
self.log.info(f"Selected used coin: {coin.name()}")
2020-03-19 11:26:51 +03:00
if sum >= amount:
2020-04-01 04:59:14 +03:00
self.log.info(f"Successfully selected coins: {used_coins}")
2020-03-19 11:26:51 +03:00
return used_coins
else:
# This shouldn't happen because of: if amount > self.get_unconfirmed_balance_spendable():
2020-04-01 07:02:07 +03:00
self.log.error(
f"Wasn't able to select coins for amount: {amount}"
f"unspent: {unspent}"
f"unconfirmed_removals: {unconfirmed_removals}"
f"unconfirmed_additions: {unconfirmed_additions}"
)
2020-03-19 11:26:51 +03:00
return None
2020-02-13 22:57:40 +03:00
async def generate_unsigned_transaction(
2020-03-23 22:59:53 +03:00
self,
amount: uint64,
2020-03-23 22:59:53 +03:00
newpuzzlehash: bytes32,
fee: uint64 = uint64(0),
2020-03-23 22:59:53 +03:00
origin_id: bytes32 = None,
coins: Set[Coin] = None,
2020-02-13 22:57:40 +03:00
) -> List[Tuple[Program, CoinSolution]]:
2020-03-06 02:53:36 +03:00
"""
Generates a unsigned transaction in form of List(Puzzle, Solutions)
"""
if coins is None:
coins = await self.select_coins(amount + fee)
if coins is None:
2020-04-01 04:59:14 +03:00
self.log.info(f"coins is None")
2020-02-13 22:57:40 +03:00
return []
2020-03-06 02:53:36 +03:00
2020-04-01 04:59:14 +03:00
self.log.info(f"coins is not None {coins}")
spend_value = sum([coin.amount for coin in coins])
2020-02-12 04:01:39 +03:00
change = spend_value - amount - fee
2020-03-06 02:53:36 +03:00
spends: List[Tuple[Program, CoinSolution]] = []
output_created = False
for coin in coins:
2020-04-01 04:59:14 +03:00
self.log.info(f"coin from coins {coin}")
2020-03-06 02:53:36 +03:00
# Get keys for puzzle_hash
2020-02-12 04:01:39 +03:00
puzzle_hash = coin.puzzle_hash
2020-04-15 03:44:17 +03:00
maybe = await self.wallet_state_manager.get_keys(puzzle_hash)
2020-02-13 22:57:40 +03:00
if not maybe:
2020-04-01 07:02:07 +03:00
self.log.error(
f"Wallet couldn't find keys for puzzle_hash {puzzle_hash}"
)
2020-02-13 22:57:40 +03:00
return []
2020-03-06 02:53:36 +03:00
# Get puzzle for pubkey
2020-02-13 22:57:40 +03:00
pubkey, secretkey = maybe
puzzle: Program = puzzle_for_pk(bytes(pubkey))
2020-03-06 02:53:36 +03:00
# Only one coin creates outputs
if output_created is False and origin_id is None:
primaries = [{"puzzlehash": newpuzzlehash, "amount": amount}]
if change > 0:
changepuzzlehash = await self.get_new_puzzlehash()
primaries.append({"puzzlehash": changepuzzlehash, "amount": change})
2020-04-20 08:08:16 +03:00
if fee > 0:
solution = self.make_solution(primaries=primaries, fee=fee)
else:
solution = self.make_solution(primaries=primaries)
output_created = True
elif output_created is False and origin_id == coin.name():
2020-02-13 22:57:40 +03:00
primaries = [{"puzzlehash": newpuzzlehash, "amount": amount}]
2020-02-12 04:01:39 +03:00
if change > 0:
changepuzzlehash = await self.get_new_puzzlehash()
2020-02-13 22:57:40 +03:00
primaries.append({"puzzlehash": changepuzzlehash, "amount": change})
2020-02-24 20:16:47 +03:00
2020-04-20 08:08:16 +03:00
if fee > 0:
solution = self.make_solution(primaries=primaries, fee=fee)
else:
solution = self.make_solution(primaries=primaries)
2020-02-12 04:01:39 +03:00
output_created = True
else:
2020-04-20 08:08:16 +03:00
solution = self.make_solution()
2020-03-06 02:53:36 +03:00
2020-02-12 04:01:39 +03:00
spends.append((puzzle, CoinSolution(coin, solution)))
2020-04-01 04:59:14 +03:00
self.log.info(f"Spends is {spends}")
2020-02-12 04:01:39 +03:00
return spends
async def sign_transaction(
self, spends: List[Tuple[Program, CoinSolution]]
) -> Optional[SpendBundle]:
2020-03-06 02:53:36 +03:00
signatures = []
2020-02-13 22:57:40 +03:00
for puzzle, solution in spends:
2020-03-06 02:53:36 +03:00
# Get keys
2020-04-15 09:40:36 +03:00
keys = await self.wallet_state_manager.get_keys(solution.coin.puzzle_hash)
2020-02-13 22:57:40 +03:00
if not keys:
2020-04-01 07:02:07 +03:00
self.log.error(
f"Sign transaction failed, No Keys for puzzlehash {solution.coin.puzzle_hash}"
)
2020-02-13 22:57:40 +03:00
return None
2020-04-01 04:59:14 +03:00
2020-02-13 22:57:40 +03:00
pubkey, secretkey = keys
secretkey = BLSPrivateKey(secretkey)
code_ = [puzzle, solution.solution]
sexp = clvm.to_sexp_f(code_)
2020-03-06 02:53:36 +03:00
# Get AGGSIG conditions
2020-02-27 04:33:25 +03:00
err, con, cost = conditions_for_solution(sexp)
2020-02-13 22:57:40 +03:00
if err or not con:
2020-04-01 04:59:14 +03:00
self.log.error(f"Sign transcation failed, con:{con}, error: {err}")
2020-02-13 22:57:40 +03:00
return None
2020-04-01 04:59:14 +03:00
2020-02-13 22:57:40 +03:00
conditions_dict = conditions_by_opcode(con)
2020-03-06 02:53:36 +03:00
# Create signature
2020-03-26 00:36:32 +03:00
for pk_message in hash_key_pairs_for_conditions_dict(
conditions_dict, bytes(solution.coin)
):
2020-03-06 02:53:36 +03:00
signature = secretkey.sign(pk_message.message_hash)
signatures.append(signature)
# Aggregate signatures
aggsig = BLSSignature.aggregate(signatures)
2020-02-13 22:57:40 +03:00
solution_list: List[CoinSolution] = [
CoinSolution(
coin_solution.coin, clvm.to_sexp_f([puzzle, coin_solution.solution])
)
for (puzzle, coin_solution) in spends
]
spend_bundle = SpendBundle(solution_list, aggsig)
2020-03-06 02:53:36 +03:00
2020-02-13 22:57:40 +03:00
return spend_bundle
2020-03-19 11:26:51 +03:00
async def generate_signed_transaction_dict(
self, data: Dict[str, Any]
2020-04-28 04:42:08 +03:00
) -> Optional[TransactionRecord]:
2020-03-19 11:26:51 +03:00
""" Use this to generate transaction. """
# Check that both are integers
if not isinstance(data["amount"], int) or not isinstance(data["amount"], int):
raise ValueError("An integer amount or fee is required (too many decimals)")
amount = uint64(data["amount"])
2020-03-19 11:26:51 +03:00
if "fee" in data:
fee = uint64(data["fee"])
2020-03-19 11:26:51 +03:00
else:
fee = uint64(0)
2020-03-19 11:26:51 +03:00
puzzle_hash = bytes32(bytes.fromhex(data["puzzle_hash"]))
2020-03-19 11:26:51 +03:00
return await self.generate_signed_transaction(amount, puzzle_hash, fee)
2020-02-13 22:57:40 +03:00
async def generate_signed_transaction(
2020-03-23 22:59:53 +03:00
self,
amount: uint64,
puzzle_hash: bytes32,
fee: uint64 = uint64(0),
2020-03-23 22:59:53 +03:00
origin_id: bytes32 = None,
coins: Set[Coin] = None,
2020-04-28 04:42:08 +03:00
) -> Optional[TransactionRecord]:
2020-02-25 04:19:50 +03:00
""" Use this to generate transaction. """
2020-03-19 11:26:51 +03:00
2020-03-23 22:59:53 +03:00
transaction = await self.generate_unsigned_transaction(
amount, puzzle_hash, fee, origin_id, coins
)
2020-02-13 22:57:40 +03:00
if len(transaction) == 0:
2020-04-01 04:59:14 +03:00
self.log.info("Unsigned transaction not generated")
2020-02-13 22:57:40 +03:00
return None
2020-04-01 04:59:14 +03:00
2020-04-01 07:00:49 +03:00
self.log.info("About to sign a transaction")
2020-04-28 04:42:08 +03:00
spend_bundle: Optional[SpendBundle] = await self.sign_transaction(transaction)
if spend_bundle is None:
return None
2020-02-13 22:57:40 +03:00
2020-04-28 04:42:08 +03:00
now = uint64(int(time.time()))
add_list: List[Coin] = []
rem_list: List[Coin] = []
for add in spend_bundle.additions():
add_list.append(add)
for rem in spend_bundle.removals():
rem_list.append(rem)
tx_record = TransactionRecord(
confirmed_at_index=uint32(0),
created_at_time=now,
to_puzzle_hash=puzzle_hash,
amount=uint64(amount),
fee_amount=uint64(fee),
incoming=False,
confirmed=False,
sent=uint32(0),
spend_bundle=spend_bundle,
additions=add_list,
removals=rem_list,
wallet_id=self.wallet_info.id,
sent_to=[],
2020-03-19 22:11:58 +03:00
)
2020-04-21 16:55:59 +03:00
2020-04-28 04:42:08 +03:00
return tx_record
async def push_transaction(self, tx: TransactionRecord) -> None:
""" Use this API to send transactions. """
await self.wallet_state_manager.add_pending_transaction(tx)
2020-04-21 16:55:59 +03:00
# This is also defined in CCWallet as get_sigs()
# I think this should be a the default way the wallet gets signatures in sign_transaction()
2020-04-22 09:56:48 +03:00
async def get_sigs_for_innerpuz_with_innersol(
self, innerpuz: Program, innersol: Program
) -> List[BLSSignature]:
2020-04-21 16:55:59 +03:00
puzzle_hash = innerpuz.get_tree_hash()
pubkey, private = await self.wallet_state_manager.get_keys(puzzle_hash)
private = BLSPrivateKey(private)
sigs: List[BLSSignature] = []
code_ = [innerpuz, innersol]
sexp = Program.to(code_)
error, conditions, cost = conditions_dict_for_solution(sexp)
if conditions is not None:
for _ in hash_key_pairs_for_conditions_dict(conditions):
signature = private.sign(_.message_hash)
sigs.append(signature)
return sigs
# Create an offer spend bundle for chia given an amount of relative change (i.e -400 or 1000)
2020-04-22 09:56:48 +03:00
2020-04-21 16:55:59 +03:00
# This is to be aggregated together with a coloured coin offer to ensure that the trade happens
2020-04-24 08:30:37 +03:00
async def create_spend_bundle_relative_chia(
self, chia_amount: int, exclude: List[Coin]
):
2020-04-21 16:55:59 +03:00
list_of_solutions = []
utxos = None
# If we're losing value then get coins with at least that much value
# If we're gaining value then our amount doesn't matter
if chia_amount < 0:
utxos = await self.select_coins(abs(chia_amount), exclude)
2020-04-21 16:55:59 +03:00
else:
utxos = await self.select_coins(0, exclude)
2020-04-21 16:55:59 +03:00
if utxos is None:
return None
# Calculate output amount given sum of utxos
spend_value = sum([coin.amount for coin in utxos])
chia_amount = spend_value + chia_amount
# Create coin solutions for each utxo
output_created = None
2020-04-22 09:56:48 +03:00
sigs: List[BLSSignature] = []
2020-04-21 16:55:59 +03:00
for coin in utxos:
2020-04-22 09:56:48 +03:00
pubkey, secretkey = await self.wallet_state_manager.get_keys(
coin.puzzle_hash
)
2020-04-21 16:55:59 +03:00
puzzle = self.puzzle_for_pk(bytes(pubkey))
if output_created is None:
newpuzhash = await self.get_new_puzzlehash()
primaries = [{"puzzlehash": newpuzhash, "amount": chia_amount}]
solution = self.make_solution(primaries=primaries)
output_created = coin
else:
solution = self.make_solution(consumed=[output_created.name()])
list_of_solutions.append(
CoinSolution(coin, clvm.to_sexp_f([puzzle, solution]))
)
new_sigs = await self.get_sigs_for_innerpuz_with_innersol(puzzle, solution)
sigs = sigs + new_sigs
aggsig = BLSSignature.aggregate(sigs)
spend_bundle = SpendBundle(list_of_solutions, aggsig)
return spend_bundle