block tool move

This commit is contained in:
Yostra 2020-06-29 17:55:50 +02:00 committed by Gene Hoffman
parent 021f96caa5
commit ffb39ace45
9 changed files with 147 additions and 100 deletions

View File

@ -18,6 +18,8 @@ from src.cmds.init import check_keys
from src.server.outbound_message import NodeType, OutboundMessage, Message, Delivery
from src.simulator.simulator_protocol import FarmNewBlockProtocol
from src.util.ints import uint64, uint32
from src.wallet.trade_record import TradeRecord
from src.wallet.util.cc_utils import trade_record_to_dict
from src.wallet.util.wallet_types import WalletType
from src.wallet.rl_wallet.rl_wallet import RLWallet
from src.wallet.cc_wallet.cc_wallet import CCWallet
@ -64,27 +66,44 @@ class WalletRpcApi:
"/delete_key": self.delete_key,
"/delete_all_keys": self.delete_all_keys,
"/get_private_key": self.get_private_key,
"/get_trades": self.get_trades,
"/get_trade": self.get_trade,
"/get_all_trades": self.get_all_trades,
"/cancel_trade": self.cancel_trade,
}
async def get_trades(self, request: Dict):
async def get_trade(self, request: Dict):
if self.service is None:
return {"success": False}
if self.service.wallet_state_manager is None:
return {"success": False}
all = request["all"]
trade_mgr = self.service.wallet_state_manager.trade_manager
if all:
all_trades = await trade_mgr.get_all_trades()
result = []
for trade in all_trades:
result.append(trade.to_ui_dict())
else:
trade_id = request["trade_id"]
trade = await trade_mgr.get_trade_by_id(trade_id)
result = [trade.to_ui_dict()]
trade_id = request["trade_id"]
trade: Optional[TradeRecord] = await trade_mgr.get_trade_by_id(trade_id)
if trade is None:
response = {
f"success": False,
"error": "No trade with trade id: {trade_id}",
}
return response
result = trade_record_to_dict(trade)
response = {"success": True, "trade": result}
return response
async def get_all_trades(self, request: Dict):
if self.service is None:
return {"success": False}
if self.service.wallet_state_manager is None:
return {"success": False}
trade_mgr = self.service.wallet_state_manager.trade_manager
all_trades = await trade_mgr.get_all_trades()
result = []
for trade in all_trades:
result.append(trade_record_to_dict(trade))
response = {"success": True, "trades": result}
return response
@ -97,7 +116,7 @@ class WalletRpcApi:
wsm = self.service.wallet_state_manager
secure = request["secure"]
trade_id = request["trade_id"]
trade_id = hexstr_to_bytes(request["trade_id"])
if secure:
await wsm.trade_manager.cancel_pending_offer_safely(trade_id)
@ -458,7 +477,7 @@ class WalletRpcApi:
spend_bundle,
error,
) = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids(
offer
offer, file_name
)
if success:
self.service.wallet_state_manager.trade_manager.write_offer_to_disk(

View File

@ -15,6 +15,9 @@ from src.types.spend_bundle import SpendBundle
from src.types.header import Header
from src.util.api_decorators import api_request
from src.util.ints import uint64
from src.util.block_tools import BlockTools
bt = BlockTools()
bt: Optional[BlockTools] = None
OutboundMessageGenerator = AsyncGenerator[OutboundMessage, None]
@ -136,9 +139,6 @@ class FullNodeSimulator(FullNode):
program = best_solution_program(bundle)
dict_h[top_tip.height + 1] = (program, bundle.aggregated_signature)
fees = bundle.fees()
from tests.block_tools import BlockTools
bt = BlockTools()
more_blocks = bt.get_consecutive_blocks(
self.constants.copy(),
@ -165,9 +165,6 @@ class FullNodeSimulator(FullNode):
current_blocks = await self.get_current_blocks(top_tip)
block_count = new_index - old_index
from tests.block_tools import BlockTools
bt = BlockTools()
more_blocks = bt.get_consecutive_blocks(
self.constants.copy(),

View File

@ -9,7 +9,6 @@ from src.util.path import mkdir, path_from_root
from src.simulator.full_node_simulator import FullNodeSimulator
from src.simulator.simulator_constants import test_constants
from src.types.peer_info import PeerInfo
# See: https://bugs.python.org/issue29288
u"".encode("idna")
@ -18,7 +17,7 @@ u"".encode("idna")
def service_kwargs_for_full_node(root_path):
service_name = "full_node"
config = load_config_cli(root_path, "config.yaml", service_name)
config = load_config_cli(root_path, "config.yaml", "full_node")
db_path = path_from_root(root_path, config["simulator_database_path"])
mkdir(db_path.parent)
@ -31,9 +30,6 @@ def service_kwargs_for_full_node(root_path):
override_constants=test_constants,
)
introducer = config["introducer_peer"]
peer_info = PeerInfo(introducer["host"], introducer["port"])
async def start_callback():
await api._start()
@ -55,11 +51,6 @@ def service_kwargs_for_full_node(root_path):
stop_callback=stop_callback,
await_closed_callback=await_closed_callback,
rpc_info=(FullNodeRpcApi, config["rpc_port"]),
periodic_introducer_poll=(
peer_info,
config["introducer_connect_interval"],
config["target_peer_count"],
),
)
return kwargs

View File

@ -18,6 +18,8 @@ from blspy import (
from chiavdf import prove
from chiabip158 import PyBIP158
from chiapos import DiskPlotter, DiskProver
from src.consensus.coinbase import create_puzzlehash_for_pk
from src.consensus.constants import ConsensusConstants
from src.cmds.init import create_default_chia_config, initialize_ssl
@ -47,7 +49,6 @@ from src.util.significant_bits import truncate_to_significant_bits
from src.util.mempool_check_conditions import get_name_puzzle_conditions
from src.plotting.plot_tools import load_plots
from src.util.logging import initialize_logging
from tests.wallet_tools import WalletTool

View File

@ -25,6 +25,7 @@ from src.wallet.trade_record import TradeRecord
from src.wallet.trading.trade_status import TradeStatus
from src.wallet.trading.trade_store import TradeStore
from src.wallet.transaction_record import TransactionRecord
from src.wallet.util.cc_utils import get_discrepancies_for_spend_bundle
from src.wallet.wallet import Wallet
from clvm_tools import binutils
@ -72,9 +73,9 @@ class TradeManager:
additions = {}
for trade in all_pending:
for coin in trade.spend_bundle.removals():
for coin in trade.removals:
removals[coin.name()] = coin
for coin in trade.spend_bundle.additions():
for coin in trade.additions:
additions[coin.name()] = coin
return removals, additions
@ -174,9 +175,14 @@ class TradeManager:
result = {}
for trade_offer in all_pending:
locked = await self.get_locked_coins_in_spend_bundle(
trade_offer.spend_bundle
)
if trade_offer.tx_spend_bundle is None:
locked = await self.get_locked_coins_in_spend_bundle(
trade_offer.spend_bundle
)
else:
locked = await self.get_locked_coins_in_spend_bundle(
trade_offer.tx_spend_bundle
)
for name, record in locked.items():
if wallet_id is None or record.wallet_id == wallet_id:
result[name] = record
@ -216,7 +222,7 @@ class TradeManager:
if trade is None:
return None
all_coins = trade.spend_bundle.removals()
all_coins = trade.removals
for coin in all_coins:
wallet = await self.wallet_state_manager.get_wallet_for_coin(coin.name())
@ -325,6 +331,7 @@ class TradeManager:
my_offer=True,
sent=uint32(0),
spend_bundle=spend_bundle,
tx_spend_bundle=None,
additions=spend_bundle.additions(),
removals=spend_bundle.removals(),
trade_id=std_hash(spend_bundle.name() + bytes(now)),
@ -341,58 +348,13 @@ class TradeManager:
if offer is not None:
file_path.write_text(bytes(offer).hex())
async def get_discrepancies_for_spend_bundle(
self, trade_offer: SpendBundle
) -> Tuple[bool, Optional[Dict], Optional[Exception]]:
try:
cc_discrepancies: Dict[bytes32, int] = dict()
for coinsol in trade_offer.coin_solutions:
puzzle = coinsol.solution.first()
solution = coinsol.solution.rest().first()
# work out the deficits between coin amount and expected output for each
if cc_wallet_puzzles.check_is_cc_puzzle(puzzle):
parent_info = binutils.disassemble(solution.rest().first()).split(
" "
)
if len(parent_info) > 1:
colour = cc_wallet_puzzles.get_genesis_from_puzzle(
binutils.disassemble(puzzle)
)
# get puzzle and solution
innerpuzzlereveal = solution.rest().rest().rest().first()
innersol = solution.rest().rest().rest().rest().first()
# Get output amounts by running innerpuzzle and solution
out_amount = cc_wallet_puzzles.get_output_amount_for_puzzle_and_solution(
innerpuzzlereveal, innersol
)
# add discrepancy to dict of discrepancies
if colour in cc_discrepancies:
cc_discrepancies[colour] += coinsol.coin.amount - out_amount
else:
cc_discrepancies[colour] = coinsol.coin.amount - out_amount
else: # standard chia coin
coin_amount = coinsol.coin.amount
out_amount = cc_wallet_puzzles.get_output_amount_for_puzzle_and_solution(
puzzle, solution
)
diff = coin_amount - out_amount
if "chia" in cc_discrepancies:
cc_discrepancies["chia"] = cc_discrepancies["chia"] + diff
else:
cc_discrepancies["chia"] = diff
return True, cc_discrepancies, None
except Exception as e:
return False, None, e
async def get_discrepancies_for_offer(
self, file_path: Path
) -> Tuple[bool, Optional[Dict], Optional[Exception]]:
self.log.info(f"trade offer: {file_path}")
trade_offer_hex = file_path.read_text()
trade_offer = TradeRecord.from_bytes(bytes.fromhex(trade_offer_hex))
return await self.get_discrepancies_for_spend_bundle(trade_offer.spend_bundle)
return get_discrepancies_for_spend_bundle(trade_offer.spend_bundle)
async def get_inner_puzzle_for_puzzle_hash(self, puzzle_hash) -> Optional[Program]:
info = await self.wallet_state_manager.puzzle_store.get_derivation_record_for_puzzle_hash(
@ -830,7 +792,8 @@ class TradeManager:
created_at_time=now,
my_offer=False,
sent=uint32(0),
spend_bundle=spend_bundle,
spend_bundle=offer_spend_bundle,
tx_spend_bundle=spend_bundle,
additions=spend_bundle.additions(),
removals=spend_bundle.removals(),
trade_id=std_hash(spend_bundle.name() + bytes(now)),

View File

@ -1,12 +1,11 @@
from dataclasses import dataclass
from typing import Optional, List, Tuple, Dict
from typing import Optional, List, Tuple
from src.types.coin import Coin
from src.types.spend_bundle import SpendBundle
from src.types.sized_bytes import bytes32
from src.util.streamable import Streamable, streamable
from src.util.ints import uint32, uint64, uint8
from src.wallet.trading.trade_status import TradeStatus
@dataclass(frozen=True)
@ -21,21 +20,10 @@ class TradeRecord(Streamable):
created_at_time: uint64
my_offer: bool
sent: uint32
spend_bundle: SpendBundle
spend_bundle: SpendBundle # This in not complete spendbundle
tx_spend_bundle: Optional[SpendBundle] # this is full trade
additions: List[Coin]
removals: List[Coin]
trade_id: bytes32
status: uint32 # TradeStatus, enum not streamable
sent_to: List[Tuple[str, uint8, Optional[str]]]
def to_ui_dict(self) -> Dict:
""" Convinence function to return only part of trade record we care about and show correct status to the ui"""
result = {}
result["trade_id"] = self.trade_id.hex()
result["sent"] = self.sent
result["my_offer"] = self.my_offer
result["created_at_time"] = self.created_at_time
result["accepted_at_time"] = self.accepted_at_time
result["confirmed_at_index"] = self.confirmed_at_index
result["status"] = TradeStatus(self.status).name
return result

View File

@ -94,6 +94,7 @@ class TradeStore:
my_offer=current.my_offer,
sent=current.sent,
spend_bundle=current.spend_bundle,
tx_spend_bundle=current.tx_spend_bundle,
additions=current.additions,
removals=current.removals,
trade_id=current.trade_id,
@ -133,6 +134,7 @@ class TradeStore:
my_offer=current.my_offer,
sent=uint32(current.sent + 1),
spend_bundle=current.spend_bundle,
tx_spend_bundle=current.tx_spend_bundle,
additions=current.additions,
removals=current.removals,
trade_id=current.trade_id,
@ -158,6 +160,7 @@ class TradeStore:
my_offer=current.my_offer,
sent=uint32(0),
spend_bundle=current.spend_bundle,
tx_spend_bundle=current.tx_spend_bundle,
additions=current.additions,
removals=current.removals,
trade_id=current.trade_id,

View File

@ -0,0 +1,85 @@
from typing import Tuple, Optional, Dict
from clvm_tools import binutils
from src.types.sized_bytes import bytes32
from src.types.spend_bundle import SpendBundle
from src.wallet.cc_wallet import cc_wallet_puzzles
from src.wallet.trade_record import TradeRecord
from src.wallet.trading.trade_status import TradeStatus
def trade_status_ui_string(status: TradeStatus):
if status is TradeStatus.PENDING_CONFIRM:
return "Pending Confirmation"
elif status is TradeStatus.CANCELED:
return "Canceled"
elif status is TradeStatus.CONFIRMED:
return "Confirmed"
elif status is TradeStatus.PENDING_CANCEL:
return "Pending Cancellation"
elif status is TradeStatus.FAILED:
return "Failed"
elif status is TradeStatus.PENDING_ACCEPT:
return "Pending"
def trade_record_to_dict(record: TradeRecord) -> Dict:
""" Convinence function to return only part of trade record we care about and show correct status to the ui"""
result = {}
result["trade_id"] = record.trade_id.hex()
result["sent"] = record.sent
result["my_offer"] = record.my_offer
result["created_at_time"] = record.created_at_time
result["accepted_at_time"] = record.accepted_at_time
result["confirmed_at_index"] = record.confirmed_at_index
result["status"] = trade_status_ui_string(TradeStatus(record.status))
success, offer_dict, error = get_discrepancies_for_spend_bundle(record.spend_bundle)
if success is False or offer_dict is None:
raise ValueError(error)
result["offer_dict"] = offer_dict
return result
def get_discrepancies_for_spend_bundle(
trade_offer: SpendBundle,
) -> Tuple[bool, Optional[Dict], Optional[Exception]]:
try:
cc_discrepancies: Dict[bytes32, int] = dict()
for coinsol in trade_offer.coin_solutions:
puzzle = coinsol.solution.first()
solution = coinsol.solution.rest().first()
# work out the deficits between coin amount and expected output for each
if cc_wallet_puzzles.check_is_cc_puzzle(puzzle):
parent_info = binutils.disassemble(solution.rest().first()).split(" ")
if len(parent_info) > 1:
colour = cc_wallet_puzzles.get_genesis_from_puzzle(
binutils.disassemble(puzzle)
)
# get puzzle and solution
innerpuzzlereveal = solution.rest().rest().rest().first()
innersol = solution.rest().rest().rest().rest().first()
# Get output amounts by running innerpuzzle and solution
out_amount = cc_wallet_puzzles.get_output_amount_for_puzzle_and_solution(
innerpuzzlereveal, innersol
)
# add discrepancy to dict of discrepancies
if colour in cc_discrepancies:
cc_discrepancies[colour] += coinsol.coin.amount - out_amount
else:
cc_discrepancies[colour] = coinsol.coin.amount - out_amount
else: # standard chia coin
coin_amount = coinsol.coin.amount
out_amount = cc_wallet_puzzles.get_output_amount_for_puzzle_and_solution(
puzzle, solution
)
diff = coin_amount - out_amount
if "chia" in cc_discrepancies:
cc_discrepancies["chia"] = cc_discrepancies["chia"] + diff
else:
cc_discrepancies["chia"] = diff
return True, cc_discrepancies, None
except Exception as e:
return False, None, e

View File

@ -1,7 +1,7 @@
from typing import Dict
from src.consensus.constants import constants
from .block_tools import BlockTools
from src.util.block_tools import BlockTools
def make_test_constants_with_genesis(test_constants_overrides: Dict):