def restore_multisig_wallet(self, storage, wallet_type): # FIXME: better handling of duplicate keys m, n = Wallet.multisig_type(wallet_type) key_list = self.request_many(n - 1) need_password = any(Wallet.should_encrypt(text) for text in key_list) password = self.request_password() if need_password else None return Wallet.from_multisig(key_list, password, storage, wallet_type)
def load_wallet(self, config): path = config.get_wallet_path() if path in self.wallets: wallet = self.wallets[path] else: storage = WalletStorage(path) wallet = Wallet(storage) wallet.start_threads(self.network) self.wallets[path] = wallet return wallet
def verify_transaction(transaction, get_balance, check_funds=True): """Verify a transaction by checking whether the sender has sufficient coins. Arguments: :transaction: The transaction that should be verified. """ if check_funds: sender_balance = get_balance(transaction.sender) return sender_balance >= transaction.amount and Wallet.verify_transaction(transaction) else: return Wallet.verify_transaction(transaction)
def register_plugin_wallet(self, name, gui_good, details): from wallet import Wallet def dynamic_constructor(storage): return self.wallet_plugin_loader(name).wallet_class(storage) if details[0] == 'hardware': self.hw_wallets[name] = (gui_good, details) self.print_error("registering wallet %s: %s" %(name, details)) Wallet.register_plugin_wallet(details[0], details[1], dynamic_constructor)
def load_wallet(self, path, wizard=None): if path in self.wallets: wallet = self.wallets[path] else: if wizard: wallet = wizard.open_wallet(self.network, path) else: storage = WalletStorage(path) wallet = Wallet(storage) wallet.start_threads(self.network) if wallet: self.wallets[path] = wallet return wallet
def load_wallet(self, path): if path in self.wallets: wallet = self.wallets[path] return wallet storage = WalletStorage(path) if not storage.file_exists: return wallet = Wallet(storage) action = wallet.get_action() if action: return wallet.start_threads(self.network) self.wallets[path] = wallet return wallet
def load_wallet(self, path): # wizard will be launched if we return if path in self.wallets: wallet = self.wallets[path] return wallet storage = WalletStorage(path) if not storage.file_exists: return if storage.requires_split() or storage.requires_upgrade() or storage.get_action(): return wallet = Wallet(storage) wallet.start_threads(self.network) self.wallets[path] = wallet return wallet
def __init__(self,): QObject.__init__(self,) self.thread = None self._balance = '<b>0.00</b>000000' self._fiatSymbol = u'€' self._fiatRate = 0 self._fiatBalance = u'0 €' self._wallet = Wallet() self._wallet.onNewTransaction.connect(self.notifyNewTx) self._walletUnlocked = False self.settings = Settings() self.addressesModel = AddressesModel() self.transactionsModel = TransactionsModel() self.timer = QTimer(self) self.timer.setInterval(900000) # 15 min update self.timer.timeout.connect(self.update) self.timer.start() if self.settings.storePassKey: self._currentPassKey = self.settings.passKey try: self.unlockWallet(self._currentPassKey) except: self.onError.emit('Stored pass phrase is invalid') else: self._currentPassKey = None self._currentAddressIndex = 0
def create_or_restore(self, storage): '''After querying the user what they wish to do, create or restore a wallet and return it.''' self.remove_from_recently_open(storage.path) # Filter out any unregistered wallet kinds registered_kinds = Wallet.categories() kinds, descriptions = zip(*[pair for pair in WizardBase.wallet_kinds if pair[0] in registered_kinds]) action, kind_index = self.query_create_or_restore(descriptions) assert action in WizardBase.user_actions kind = kinds[kind_index] if kind == 'multisig': wallet_type = self.query_multisig(action) elif kind == 'hardware': # The create/restore distinction is not obvious for hardware # wallets; so we ask for the action again and default based # on the prior choice :) hw_wallet_types, choices = self.plugins.hardware_wallets(action) msg = _('Select the type of hardware wallet: ') action, choice = self.query_hw_wallet_choice(msg, action, choices) wallet_type = hw_wallet_types[choice] elif kind == 'twofactor': wallet_type = '2fa' else: wallet_type = 'standard' if action == 'create': wallet = self.create_wallet(storage, wallet_type, kind) else: wallet = self.restore_wallet(storage, wallet_type, kind) return action, wallet
def add_cosigners(self, wallet): # FIXME: better handling of duplicate keys m, n = Wallet.multisig_type(wallet.wallet_type) xpub1 = wallet.master_public_keys.get("x1/") xpubs = self.request_many(n - 1, xpub1) for i, xpub in enumerate(xpubs): wallet.add_master_public_key("x%d/" % (i + 2), xpub)
def run(self, network, storage): '''The main entry point of the wizard. Open a wallet from the given filename. If the file doesn't exist launch the GUI-specific install wizard proper, created by calling create_wizard().''' need_sync = False is_restore = False if storage.file_exists: wallet = Wallet(storage) if wallet.imported_keys: self.update_wallet_format(wallet) else: cr, wallet = self.create_or_restore(storage) if not wallet: return need_sync = True is_restore = (cr == 'restore') while True: action = wallet.get_action() if not action: break need_sync = True self.run_wallet_action(wallet, action) # Save the wallet after each action wallet.storage.write() if network: # Show network dialog if config does not exist if self.config.get('auto_connect') is None: self.choose_server(network) else: self.show_warning(_('You are offline')) if need_sync: self.create_addresses(wallet) # start wallet threads if network: wallet.start_threads(network) if is_restore: self.show_restore(wallet, network) self.finished() return wallet
def main(): try: wallet_id = sys.argv[1] sample_wallet = None try: sample_wallet = Wallet(wallet_label=wallet_id, iterate_until_send=True) except http.WalletNotFoundError: print "Couldn't find that wallet." sys.exit() for utxos in sample_wallet: print "UTXOs: %s" % str(utxos) print("Desired Spend (in satoshis): %d" % sample_wallet.get_current_desired_spend()) except Exception as err: print "Error: %s" % str(err) print "Usage: print.py 3562f0c16b41b2f9"
def load_wallet(self, path, get_wizard=None): if path in self.wallets: wallet = self.wallets[path] else: storage = WalletStorage(path) if storage.file_exists: wallet = Wallet(storage) action = wallet.get_action() else: action = 'new' if action: if get_wizard is None: return None wizard = get_wizard() wallet = wizard.run(self.network, storage) else: wallet.start_threads(self.network) if wallet: self.wallets[path] = wallet return wallet
def open_wallet(self, network, filename): '''The main entry point of the wizard. Open a wallet from the given filename. If the file doesn't exist launch the GUI-specific install wizard proper.''' storage = WalletStorage(filename) if storage.file_exists: wallet = Wallet(storage) self.update_wallet_format(wallet) task = None else: cr, wallet = self.create_or_restore(storage) if not wallet: return task = lambda: self.show_restore(wallet, network, cr) need_sync = False while True: action = wallet.get_action() if not action: break need_sync = True self.run_wallet_action(wallet, action) # Save the wallet after each action wallet.storage.write() if network: self.choose_server(network) else: self.show_warning(_('You are offline')) if need_sync: self.create_addresses(wallet) # start wallet threads if network: wallet.start_threads(network) if task: task() return wallet
class Cashier: _exchanges = exchanges.actived_exchanges def __init__(self): self.wallet = Wallet() self.qty_per_order = config.configuration['qty_per_order'] def post_transfers(self, buy_account, sell_account): '''交易完成以后的比特币转账 流程: 1. 检查钱包是否有足够余额 2.1 有余额则先发送比特币给卖方 2. 买方转移比特币到钱包 ''' buy_ex = Trader._exchanges[buy_account.name] sell_ex = Trader._exchanges[sell_account.name] wallet_balance = self.wallet.balance() if wallet_balance > self.qty_per_order: self.wallet.withdraw(sell_account.stock_deposit_address, self.qty_per_order) buy_ex.withdraw_stock(self.qty_per_order) def make_balance(self, accounts): wallet_balance = self.wallet.balance() for a in accounts: if a.stock_balance < self.qty_per_order and wallet_balance > self.qty_per_order: _logger.info('[CASHIER]\t\t Transfering BTC from wallet to account "{0}", qty={1}' .format(a.name, self.qty_per_order)) self.wallet.withdraw(a.stock_deposit_address, self.qty_per_order) wallet_balance -= self.qty_per_order
def load_wallet(self, path, password): # wizard will be launched if we return if path in self.wallets: wallet = self.wallets[path] return wallet storage = WalletStorage(path) if not storage.file_exists(): return if storage.is_encrypted(): if not password: return storage.decrypt(password) if storage.requires_split(): return if storage.requires_upgrade(): self.print_error('upgrading wallet format') storage.upgrade() if storage.get_action(): return wallet = Wallet(storage) wallet.start_threads(self.network) self.wallets[path] = wallet return wallet
def verify_transaction(transaction, get_balance, check_funds=True): """Verify sender has sufficient balance to allow transaction to be processed""" if check_funds: sender_balance = get_balance(transaction.sender) if sender_balance < transaction.amount: print('Transaction amount {} exceeds balance {}'.format(transaction.amount, sender_balance)) print('Insufficient balance!') return False if not Wallet.verify_transaction(transaction): print('Bad signature => %s' % transaction.signature) print('Signature verification failed!') return False return True
def new(self): name = os.path.basename(self.storage.path) title = _("Welcome to the Electrum installation wizard.") message = '\n'.join([ _("The wallet '%s' does not exist.") % name, _("What kind of wallet do you want to create?") ]) wallet_kinds = [ ('standard', _("Standard wallet")), ('twofactor', _("Wallet with two-factor authentication")), ('multisig', _("Multi-signature wallet")), ] registered_kinds = Wallet.categories() choices = wallet_kinds#[pair for pair in wallet_kinds if pair[0] in registered_kinds] self.choice_dialog(title=title, message=message, choices=choices, run_next=self.on_wallet_type)
class Application(QtGui.QApplication): STATUS_REPLENISH = 0 STATUS_CONFIRMATION = 1 STATUS_WORK = 2 statusChanged = QtCore.pyqtSignal(int, int, name='changeStatus') def __init__(self, args): QtGui.QApplication.__init__(self, []) self.isTestNet = args['testnet'] self.dataDir = args['datadir'] self._status = None def _install_i18n(self): import __builtin__ __builtin__.__dict__["_"] = lambda x: x def exec_(self): self._install_i18n() from wallet import Wallet self.wallet = Wallet(self.dataDir, self.isTestNet) self.wallet.balanceUpdated.connect(self._check_status) from mainwindow import MainWindow self.mainWindow = MainWindow() self.mainWindow.show() self.wallet.sync_start() QtCore.QTimer.singleShot(0, self._check_status) retval = super(QtGui.QApplication, self).exec_() self.mainWindow.chatpage.sync_stop() self.wallet.sync_stop() return retval def _check_status(self): moniker = clubAsset['monikers'][0] available_balance = self.wallet.get_available_balance(moniker) unconfirmed_balance = self.wallet.get_unconfirmed_balance(moniker) if available_balance > 0: self._set_new_status(self.STATUS_WORK) else: if unconfirmed_balance > 0: self._set_new_status(self.STATUS_CONFIRMATION) else: self._set_new_status(self.STATUS_REPLENISH) def _set_new_status(self, status): if self._status == status: return oldStatus = self._status self._status = status self.statusChanged.emit(oldStatus, status)
def exec_(self): self._install_i18n() from wallet import Wallet self.wallet = Wallet(self.dataDir, self.isTestNet) self.wallet.balanceUpdated.connect(self._check_status) from mainwindow import MainWindow self.mainWindow = MainWindow() self.mainWindow.show() self.wallet.sync_start() QtCore.QTimer.singleShot(0, self._check_status) retval = super(QtGui.QApplication, self).exec_() self.mainWindow.chatpage.sync_stop() self.wallet.sync_stop() return retval
def mine_block(self): """Create a new block and add open transactions to it.""" # Fetch the currently last block of the blockchain print(self.public_key) if self.public_key == None: return None last_block = self.__chain[-1] # Hash the last block (=> to be able to compare it to the stored hash value) hashed_block = hash_block(last_block) proof = self.proof_of_work() # Miners should be rewarded, so let's create a reward transaction # reward_transaction = { # "sender": "MINNER", # "recipient": owner, # "amount": MINING_REWARD # } reward_transaction = Transaction( 'MINING', self.public_key, '', MINING_REWARD) # Copy transaction instead of manipulating the original open_transactions list # This ensures that if for some reason the mining should fail, we don't have the reward transaction stored in the open transactions copied_transactions = self.__open_transactions[:] for tx in copied_transactions: if not Wallet.verify_transaction(tx): return False copied_transactions.append(reward_transaction) block = Block(len(self.__chain), hashed_block, copied_transactions, proof) self.__chain.append(block) self.__open_transactions = [] self.save_data() for node in self.__peer_nodes: url = 'http://{}/broadcast-block'.format(node) coverted_block = block.__dict__.copy() coverted_block['transactions'] = [ tx.__dict__ for tx in coverted_block['transactions']] try: response = requests.post(url, json={'block': coverted_block}) if response.status_code == 400 and response.status_code == 500: print('Block declined, needs resolving') if response.status_code == 409: self.resolve_conflicts = True except requests.exceptions.ConnectionError: continue return block
def mine_block(self): """Mine the outstanding, pending transactions and commit them to a new block. Add the mining reward as a new pending transaction. """ if self.__public_key is None: return None last_block = self.__chain[-1] hashed_block = hash_block(last_block) proof = self.proof_of_work() reward_transaction = Transaction('MINING', self.__public_key, '', MINING_REWARD) copied_transactions = self.__open_transactions[:] for tx in copied_transactions: if not Wallet.verify_transaction(tx): return None copied_transactions.append(reward_transaction) block = Block(len(self.__chain), hashed_block, copied_transactions, proof) self.__chain.append(block) self.__open_transactions = [] self.save_data() for node in self.__peer_nodes: url = 'http://{}/broadcast-block'.format(node) converted_block = block.__dict__.copy() converted_block['transactions'] = [tx.__dict__ for tx in block.transactions] try: response = requests.post(url, json={ 'block': converted_block }) if response.status_code == 400 or response.status_code == 500: print('Block declined, needs resolving') if response.status_code == 409: self.resolve_conflicts = True except requests.exceptions.ConnectionError: continue return block
def create_or_restore(self, storage): '''After querying the user what they wish to do, create or restore a wallet and return it.''' self.remove_from_recently_open(storage.path) # Filter out any unregistered wallet kinds registered_kinds = Wallet.categories() kinds, descriptions = zip(*[pair for pair in WizardBase.wallet_kinds if pair[0] in registered_kinds]) action, kind_index = self.query_create_or_restore(descriptions) assert action in WizardBase.user_actions kind = kinds[kind_index] if kind == 'multisig': wallet_type = self.query_multisig(action) elif kind == 'hardware': hw_wallet_types, choices = self.plugins.hardware_wallets(action) if choices: msg = _('Select the type of hardware wallet: ') else: msg = ' '.join([ _('No hardware wallet support found on your system.'), _('Please install the relevant libraries (eg python-trezor for Trezor).'), ]) choice = self.query_hw_wallet_choice(msg, choices) wallet_type = hw_wallet_types[choice] elif kind == 'twofactor': wallet_type = '2fa' else: wallet_type = 'standard' if action == 'create': wallet = self.create_wallet(storage, wallet_type, kind) else: wallet = self.restore_wallet(storage, wallet_type, kind) return action, wallet
from wallet import Wallet wallet = Wallet() address = wallet.getnewaddress() print address
def test_wallets_have_different_addresses(self): w1 = Wallet(self.UTXOs) w2 = Wallet(self.UTXOs) self.assertNotEqual(w1.address, w2.address)
def test_default_initial_amount(): wallet = Wallet() assert wallet.balance == 0
def restore_standard_wallet(self, storage): text = self.request_seed(MSG_ENTER_ANYTHING) need_password = Wallet.should_encrypt(text) password = self.request_password() if need_password else None return Wallet.from_text(text, password, storage)
def test_setting_initial_amount(): wallet = Wallet(100) assert wallet.balance == 100
def test_wallet_add_cash(): wallet = Wallet(10) wallet.add_cash(90) assert wallet.balance == 100
def loader(): plugin = self.wallet_plugin_loader(name) Wallet.register_constructor(details[0], details[1], plugin.wallet_class)
def run(self, network, storage): '''The main entry point of the wizard. Open a wallet from the given filename. If the file doesn't exist launch the GUI-specific install wizard proper, created by calling create_wizard().''' need_sync = False is_restore = False if storage.file_exists: wallet = Wallet(storage) if wallet.imported_keys: self.update_wallet_format(wallet) action = wallet.get_action() if action != 'new': self.hide() path = storage.path msg = _("The file '%s' contains an incompletely created wallet.\n" "Do you want to complete its creation now?") % path if not self.question(msg): if self.question(_("Do you want to delete '%s'?") % path): import os os.remove(path) self.show_warning(_('The file was removed')) return return self.show() else: cr, wallet = self.create_or_restore(storage) if not wallet: return need_sync = True is_restore = (cr == 'restore') while True: action = wallet.get_action() if not action: break need_sync = True self.run_wallet_action(wallet, action) # Save the wallet after each action wallet.storage.write() if network: # Show network dialog if config does not exist if self.config.get('auto_connect') is None: self.choose_server(network) else: self.show_warning(_('You are offline')) if need_sync: self.create_addresses(wallet) # start wallet threads if network: wallet.start_threads(network) if is_restore: self.show_restore(wallet, network) self.finished() return wallet
def test_create_wallet(self): w = Wallet(self.UTXOs)
from wallet import Wallet wallet = Wallet() toaddress = wallet.getnewaddress() print("Available vaults") vaults = wallet.getvaults() vaults = list(vaults.itervalues()) for n, vault in enumerate(vaults): print "Id: ", n, vault['name'] + ": ", vault['balance'] index = int(input("Enter the id of the vault you want to transfer balance from: ")) fromaddress = vaults[index]['name'] amount = int(input("Enter the balance to transfer from: {}: ".format(fromaddress))) if vaults[index]['balance'] < amount + 2: print("In sufficient balance in vault, quitting") exit(2) print("Transfering: " + str(amount) + "\tfrom address: " + fromaddress + "\tto address: " + toaddress) transfered = wallet.fastwithdrawfromvault(fromaddress, toaddress, amount) if transfered: print "Transfered :", transfered, " to:", toaddress else: print "Sorry, an error occured"
def test_wallet_spend_cash(): wallet = Wallet(20) wallet.spend_cash(10) assert wallet.balance == 10
def test_wallet_spend_cash_raises_exception_on_insufficent_amount(): wallet = Wallet() with pytest.raises(InsufficentAmount): wallet.spend_cash(100)
class WalletController(QObject): onError = Signal(unicode) onConnected = Signal(bool) onTxSent = Signal(bool) onBusy = Signal() onDoubleEncrypted = Signal() onBalance = Signal() onFiatBalance = Signal() onWalletUnlocked = Signal() onCurrentBalance = Signal() onCurrentFiatBalance = Signal() onCurrentLabel = Signal() onCurrentAddress = Signal() onCurrentDoubleEncrypted = Signal() onCurrentPassKey = Signal() onCurrentWatchOnly = Signal() def __init__(self,): QObject.__init__(self,) self.thread = None self._balance = '<b>0.00</b>000000' self._fiatSymbol = u'€' self._fiatRate = 0 self._fiatBalance = u'0 €' self._wallet = Wallet() self._wallet.onNewTransaction.connect(self.notifyNewTx) self._walletUnlocked = False self.settings = Settings() self.addressesModel = AddressesModel() self.transactionsModel = TransactionsModel() self.timer = QTimer(self) self.timer.setInterval(900000) # 15 min update self.timer.timeout.connect(self.update) self.timer.start() if self.settings.storePassKey: self._currentPassKey = self.settings.passKey try: self.unlockWallet(self._currentPassKey) except: self.onError.emit('Stored pass phrase is invalid') else: self._currentPassKey = None self._currentAddressIndex = 0 def on_event_data_received(self,*args): print 'BitPurse received DATA:', args # def notifyCallback(self): # print 'ohai! received something :)' # self.service.remove_items() def notifyNewTx(self, address, datas, amount): from eventfeed import EventFeedService, EventFeedItem service = EventFeedService('BitPurse', 'BitPurse', self.on_event_data_received) item = EventFeedItem('/usr/share/icons/hicolor/80x80/apps/bitpurse.png', 'BitPurse') item.set_body('New transaction on address %s : %f BTC' % (address, amount / float(10**8))) #item.set_custom_action(self.notifyCallback) service.add_item(item) @Slot(unicode) def newAddr(self, doubleKey): try: self._wallet.createAddr(doubleKey) self.storeWallet() self.update() except (WrongPassword, DataError), err: self.onError.emit(unicode(err))
datadir = settings['db'] new_install = False # if datadir is not there, create and initialize if not os.path.isdir(datadir): new_install = True os.mkdir(datadir) os.mkdir(datadir + '/leveldb') # create blocks.dat file shutil.copy('genesis.dat', os.path.join(datadir + '/blocks.dat')) print os.path.join(datadir + '/blocks.dat') # create lock file for db with open(datadir + '/__db.001', 'a'): pass # create wallet wallet = Wallet() if new_install: # initialize wallet wallet.initialize() mempool = MemPool(log) chaindb = ChainDb(settings, settings['db'], log, mempool, wallet, netmagic, False, False) node = Node(None, log, mempool, chaindb, netmagic) peermgr = PeerManager(node, log, mempool, chaindb, netmagic) node.peermgr = peermgr wallet.chaindb = chaindb # load blocks.dat into db, if db is newly created if new_install: chaindb.loadfile(datadir + '/blocks.dat') if 'loadblock' in settings:
super(RawCoinbaseTransaction, self).__init__( sender_addr='0000000000000000000000000000000000', recepient_addr='0000000000000000000000000000000000', inputs= '0000000000000000000000000000000000000000000000000000000000000000', value=50, locktime=0) out_txid = '746f07af15f9fca472c993cd343ab3207072020b0fd3797def150473e88cbdf6' my_address = '2NEBZ1E7FqWCQsC3aETLepmADibZ7Mgnz3D' taras_address = '2NEHZANaV4s48mzmnuRanzW4nF9vLnB2you' tx = RawTransaction(my_address, taras_address, out_txid, 20, 10) # print(tx.raw_transaction(Alice_private_key)) privkey = Wallet.WIF_to_priv(my_privkey) prRed(privkey) prk = swap_bits_in_str(privkey) # print(prk) abcde = Wallet.WIF_to_priv( 'Qqj2j371SdysJ9ru9WaTnfimX2tsQKr1snvJRrNg4X6jwYnZnUoKgUhDgppodgFbQY6dB4V') prRed(abcde) raw = tx.raw_transaction(prk[2:]) raw_dict = deserialize(raw.hex()) sig_script_len = make_varint(len(tx.sig_script.hex())) pk_script_len = make_varint(len(tx.tx_out1['pk_script'].hex())) # print(sig_script_len + tx.sig_script.hex()) # print('------') # print(pk_script_len + tx.tx_out1['pk_script'].hex()) script = (sig_script_len + tx.sig_script.hex() + pk_script_len +