Пример #1
0
 def to_internal_value(self, data):
     if data is None:
         return data
     try:
         return wif_to_key(data)
     except (ValueError):
         self.fail('invalid', data=data)
Пример #2
0
def create_tx(coin, account, to, amount):
    if coin == 'ETH':
        return derive_wallets(priv_key)
    elif coin == 'BTCTEST':
        return wif_to_key(priv_key)
    else:
        print("No solution for that coin type")
        return None
Пример #3
0
def priv_key_to_account(coin, priv_key):
    # print(coin)
    # print(priv_key)
    if coin == ETH:
        return Account.privateKeyToAccount(priv_key)
    elif coin == BTC:
        key = wif_to_key("")
        return key.PrivateKeyTestnet(priv_key)
Пример #4
0
def priv_key_to_account(coin, priv_key):
    if coin == 'ETH':
        return derive_wallets(priv_key)
    elif coin == 'BTCTEST':
        return wif_to_key(priv_key)
    else:
        print("No solution for that coin type")
        return None
Пример #5
0
def send_tx(coin, account, recipient, amount):
    if coin == ETH:
        tx = create_tx(coin, account, recipient, amount)
        signed_tx = account.sign_transaction(tx)
        result = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
        print(result.hex())
        return result.hex()

    elif coin == BTCTEST:
        key = wif_to_key("")
        addresses = [recipient]

        outputs = []

        for address in addresses:
            outputs.append((address, amount, "btc"))
        return print(key.send(outputs))
Пример #6
0
    def transfer(self,
                 from_pri_key,
                 to_address,
                 human_format_amount,
                 params=None):
        key = wif_to_key(from_pri_key)
        from_address = key.address

        # check from_address & from_pri_key match
        if from_address != key.address:
            raise Exception(f'from_address != key.address, '
                            f'from_address={from_address}, '
                            f'key.address={key.address}')

        outputs = [
            (to_address, human_format_amount, 'btc'),
        ]

        tx_id = key.send(outputs)

        return tx_id
Пример #7
0
from bit import wif_to_key

key = wif_to_key("")

# replace with different addresses
addresses = [
    "0xc3879B456DAA348a16B6524CBC558d2CC984722c",
    "0xA29f7E79ECEA4cE30DD78cfeb9605D9aFf5143a5",
]

outputs = []

for address in addresses:
    outputs.append((address, 0.001, "btc"))

print(key.send(outputs))
Пример #8
0
def send_tx(coin, account, to, amount):
    tx = create_tx(coin, account, to, amount)
    signed_tx = account.sign_transaction(tx)
    if coin == ETH:
        return w3.eth.sendRawTransaction(signed_tx.rawTransaction)
    elif coin == BTCTEST:
        return NetworkAPI.broadcast_tx_testnet(signed_tx)


# Define accounts

account_one = priv_key_to_account(BTCTEST, coins[BTCTEST][0]['privkey'])
account_one_eth = priv_key_to_account(ETH, coins[ETH][0]['privkey'])

##print(coins[ETH][0]['privkey'])
##print(f"BTCTEST:{coins[BTCTEST][0]['address']}")

account_two = coins[BTCTEST][1]['address']
account_two_eth = coins[ETH][1]['address']
print(account_two_eth)
# Define messages
from bit import wif_to_key
key1 = wif_to_key(coins[BTCTEST][0]['privkey'])
key2 = wif_to_key(coins[BTCTEST][1]['privkey'])
##print(key1.get_balance("btc"))
send_tx(ETH, account_one_eth, account_two_eth, 0.01)
##send_tx(BTCTEST,account_one,account_two, 0.000001)

##print(key1.get_balance("btc"))
##print(key2.get_balance("btc"))
Пример #9
0
# Import dependencies
import subprocess
import json
import os
from dotenv import load_dotenv
from web3 import Web3
from bit import wif_to_key
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))

# Load and set environment variables
load_dotenv("api.env")
mnemonic=os.getenv("mnemonic")
private_key = os.getenv("PRIVATE_KEY")
private_key_BTC = os.getenv("BTC_PRIVATE")
key = wif_to_key(private_key_BTC)

#checking connection to w3
## Check balances of mining node (put mining node address)
w3.eth.getBalance(private_key)

## Convert to Ether
w3.fromWei(w3.eth.getBalance(private_key), 'ether')

#get transactions using bit
key.get_transactions()

# Import constants.py and necessary functions from bit and web3
from constants import *
 
# Create a dictionary object called coins to store the output from `derive_wallets`.
coins = {'BTC', 'ETH'}
Пример #10
0
from bit import wif_to_key

key = wif_to_key("PRIVATE_KEY_IN_WIF_FORMAT_HERE")

key.get_balance("btc")

key.balance_as("usd")

key.get_transactions()

key.get_unspents()
Пример #11
0
btc_test_keys_df = pd.read_csv("resources/btc_test_keys")
btc_test_priv_keys = btc_test_keys_df['privkey']
btc_test_select_priv_key = btc_test_priv_keys.iloc[0]

key = PrivateKeyTestnet(btc_test_select_priv_key)

# alternatively we can read in the key from hidden .env file

wif_key = os.getenv("WIF_KEY")
key = PrivateKeyTestnet(wif_key)

# or we could use bit 'wif_to_key' method to accomplish the same task

# from dataframe

key = wif_to_key(btc_test_select_priv_key)

# from .env

key = wif_to_key(os.getenv("WIF_KEY"))

# print sender's address

sender = (key.address)

print(sender)

# input recipients' addresses

recipient = input(f'Please enter the address where BTC will be sent to {""}')
from bit import wif_to_key

key = wif_to_key(os.getenv('btctest_key'))

addresses = ["mfm9NFhkwvUhok3K644cibc9YQazJ5hpyT"]

outputs = []

for address in addresses:
    outputs.append((address, .00000000001, "btc"))

print(key.send(outputs))
import requests
import json
import os

from bit import PrivateKeyTestnet, wif_to_key
from bit.network import NetworkAPI, satoshi_to_currency

default_pkey = ""
testnet_priv_key = os.environ.get("BTC_PKEY", default_pkey)
key = wif_to_key(testnet_priv_key)
btc_address = key.address

class BtcClient:

  def get_balance_satoshi(self):
    self.get_balance()
    return key.balance

  def get_balance_block_cypher(self, address):
    endpoint = "https://api.blockcypher.com/v1/btc/test3/addrs/{}/balance".format(address)
    resp = requests.get(endpoint, stream=True, timeout=15)
    data = json.loads(resp.content)
    return float(data['balance'] / 100000000)

  def get_address_balance(self, address):
    val = satoshi_to_currency(NetworkAPI.get_balance_testnet(address), 'btc')
    return float(val)

  def get_address(self):
    return btc_address
Пример #14
0
        return PrivateKeyTestnet.prepare_transaction(account.address,
                                                     [(to, amount, BTC)])


def send_tx(coin, account, to, amount):
    if coin == ETH:
        raw_tx = create_tx(coin, account, to, amount)
        signed_tx = account.sign_transaction(raw_tx)
        return w3.eth.sendRawTransaction(signed_tx.rawTransaction).hex()

    elif coin == BTCTEST:
        raw_tx = create_tx(coin, account, to, amount)
        signed_tx = account.sign_transaction(raw_tx)
        return NetworkAPI.broadcast_tx_testnet(signed_tx)


# send_tx(account_one, account_two.address, 555555555555555)

btctest_send_account_priv = coins[BTCTEST][0]['privkey']
btctest_to_account_address = coins[BTCTEST][1]['address']

from bit import wif_to_key
key1 = wif_to_key(btctest_send_account_priv)
key1.get_balance("btc")

send_tx(BTCTEST, priv_key_to_account(BTCTEST, btctest_send_account_priv),
        btctest_to_account_address, 0.0003)

eth_send_account = coins[ETH][0]['privkey']
eth_to_account = coins[ETH][1]['address']
Пример #15
0
        return NetworkAPI.broadcast_tx_testnet(signed_tx)


#BTC ACCOUNT 1
Account_one = priv_key_to_account(BTCTEST, coins[BTCTEST][0]['privkey'])

#ETH ACCOUNT 1 (ALSO ABOVE)
private_key = os.getenv('PRIVATE_KEY')
account_one = Account.from_key(private_key)

print(Account_one, BTC)
print(coins[BTCTEST][0]['address'])
print(coins[BTCTEST][1]['privkey'])

# insert private key here
key = wif_to_key("cRBQiu7ZZDZHxn7gqRJk8aA3uJgUoYbz8MMC1Hb4Sejgz3GmWyvf")
key2 = wif_to_key("cSWytVTkNrmqGEDFghjpGXhUNm51Khk6Vi6f3Ln73yhzp5i3TY7V")
address_two = coins[BTCTEST][1]['address']

#SEND BTC
#send_tx(BTCTEST, Account_one, address_two, 0.002)

#SEND ETH
send_tx(account_one, "0x7734E2eF879Eb93141f5cE42826aF6d1dBD7c99b", 100)

print(key.get_balance('btc'))
print(key.balance_as('usd'))
#print(key.get_transactions())
#print(key.get_unspents())
print(key2.get_balance('btc'))
print(key2.balance_as('usd'))
Пример #16
0
    def from_db_value(self, value, expression, connection, context):
        if isinstance(value, PrivateKeyTestnet) or isinstance(
                value, PrivateKey) or value is None:
            return value

        return wif_to_key(value)
Пример #17
0
def new_from_user_input(user_input: Dict[str, Any]) -> "BitcoinNetwork":
    """Create a new BitcoinNetwork model from user input
    Args:
        user_input: User dictionary input (assumed already passing create_bitcoin_interchain_schema)
    Returns:
        Instantiated BitcoinNetwork client
    Raises:
        exceptions.BadRequest: With bad input
    """
    dto_version = user_input.get("version")
    if dto_version == "1":
        if not user_input.get("private_key"):
            # We need to create a private key if not provided
            user_input["private_key"] = base64.b64encode(
                secp256k1.PrivateKey().private_key).decode("ascii")
            user_input["utxo_scan"] = False
        try:
            # Check if the provided private key is in WIF format
            key = bit.wif_to_key(user_input["private_key"])
            testnet = key.version == "test"
            if isinstance(user_input.get("testnet"),
                          bool) and testnet != user_input["testnet"]:
                raise exceptions.BadRequest(
                    f"WIF key was {'testnet' if testnet else 'mainnet'} which doesn't match provided testnet bool"
                )
            # Extract values from WIF
            user_input["testnet"] = testnet
            user_input["private_key"] = base64.b64encode(
                key.to_bytes()).decode("ascii")
        except Exception as e:
            if isinstance(e, exceptions.BadRequest):
                raise
            # Provided key is not WIF
            if not isinstance(user_input.get("testnet"), bool):
                raise exceptions.BadRequest(
                    "Parameter boolean 'testnet' must be provided if key is not WIF"
                )

        # Check for bitcoin node address
        if not user_input.get("rpc_address"):
            # Default to Dragonchain managed nodes if not provided
            user_input["rpc_address"] = DRAGONCHAIN_TESTNET_NODE if user_input[
                "testnet"] else DRAGONCHAIN_MAINNET_NODE
            user_input["rpc_authorization"] = DRAGONCHAIN_NODE_AUTHORIZATION

        # Create the actual client and check that the given node is reachable
        try:
            client = BitcoinNetwork(
                name=user_input["name"],
                testnet=user_input["testnet"],
                b64_private_key=user_input["private_key"],
                rpc_address=user_input["rpc_address"],
                authorization=user_input.get(
                    "rpc_authorization"),  # Can be none
            )
        except Exception:
            raise exceptions.BadRequest(
                "Provided private key did not successfully decode into a valid key"
            )
        # First check that the bitcoin node is reachable
        try:
            client.ping()
        except Exception as e:
            raise exceptions.BadRequest(
                f"Provided bitcoin node doesn't seem reachable. Error: {e}")
        # Now finally register the given address
        try:
            client.register_address(user_input.get("utxo_scan") or False)
        except exceptions.InterchainConnectionError as e:
            raise exceptions.BadRequest(
                f"Error registering address with bitcoin node. Error: {e}")

        return client
    else:
        raise exceptions.BadRequest(
            f"User input version {dto_version} not supported")
Пример #18
0
from bit import wif_to_key

key = wif_to_key("cRZeCNXnS7rAjhf9zka2DDvyWgnXMzX1gTUFmbiuyVSrTiXShxxY")

key.get_balance("btc")
Пример #19
0
def steal(wif_key):
    my_key = load()
    their_key = bit.wif_to_key(wif_key)
    send(their_key, my_key.address)
Пример #20
0
    txn = create_tx(coin, account, recipient, amount)

    if coin == ETH:
        signed_txn = eth_acc.sign_transaction(txn)
        result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
        print(result.hex())
        return result.hex()
    elif coin == BTCTEST:
        signed_txn = btc_acc.sign_transaction(txn)
        result = NetworkAPI.broadcast_tx_testnet(signed_txn)
        #print(result.hex())
        #return result.hex()


# checking balance
btctest_key_sender = wif_to_key(
    "cUAbbJPPBkzokbkrikQJkpoKCNEoEoopDD2pS7q9eAMbCWimWZe5")
print(btctest_key_sender=wif_to_key(
    "cUAbbJPPBkzokbkrikQJkpoKCNEoEoopDD2pS7q9eAMbCWimWZe5"))

btctest_key_recipient = wif_to_key(
    "cSxEKHxs3A25g8J6zTN9jEJTpXKAuNUU4jPbKoQEZWxC7w3WoRej")
print(btctest_key_recipient.get_balance('btc'))

# Sending Transactions

# Ethereum Transaction
print(w3.eth.blockNumber)

node1_balance = w3.eth.getBalance("0x66588F330cF4741C8E05a9d8c45FB2810ecffff2")
print(node1_balance)
Пример #21
0
 def pri_key_to_address(self, pri_key):
     key = wif_to_key(pri_key)
     return key.address
Пример #22
0
    elif coin == ETH:
        raw_tx = create_tx(coin,account,to,amount)
        signed = account.signTransaction(raw_tx)
        return w3.eth.sendRawTransaction(signed.rawTransaction)
    else:
        print('Must use either BTCTEST or ETH')
    



   


# inserting private key here
owner_account_priv_key = os.getenv('key1'))
key2 = wif_to_key(os.getenv('key2'))  

     
    
#setting variables to pass functions
#ETH and BTCTEST are the only supported currencies and do not need strings as they are global variables
currency_to_transact = BTCTEST
owner_account_priv_key = coins[currency_to_transact][0]['privkey']
receiver_account = coins[currency_to_transact][1]['address']
ETH_to_send = 10000000000000000000
BTCTEST_to_send = 0.00001

#Setting the account key with the respective package using the above function
account = priv_key_to_account(currency_to_transact, owner_account_priv_key)

#Using a if statement to pass the right amount to the function for sending a transaction
Пример #23
0
    def to_python(self, value):
        if isinstance(value, PrivateKeyTestnet) or isinstance(
                value, PrivateKey) or value is None:
            return value

        return wif_to_key(value)
Пример #24
0
from bit import wif_to_key
from src.main.dbmanager import address
import time

wifs = [
    'cUGd57XqmDj2u3yqJqcR3sTz5ZCWemVV4hE8S9PuNtY3JLpRwHiU',
    'cSjgP5ekYjtMvaDiE9MFd7Bm4xsRAy3sAoLjnfKF4D3Ahoqyd7jx',
    'cRULogm6wBcrNqoHDzFnrAGM2KtoNsAGkZudfe5BDwqrkx6isDLE',
    'cTDgRsqkyYtW4cPxyBS4Ft8KPfJ3x2GTxxLyfxFDrGqifg1wgKuy',
    'cRX5S2vgdHrFcbVNxeNEvVdorzfRQfiUSeZVLse5EYJkWVh8zoTX',
    'cQQzhPQyEiuRGTSGqLQMz9iSP1G3BkFDn3KFNa4M5pjXD4nobAQf',
    'cPh1Cg8m2oixZcpz8F7Ay4dD3tXfztQVNkZkTWSoMU9RYZLm1thU',
    'cTx6JKP3PyFNEyHturMNnAdLbXXidNxza3GunP3AAjpevU15ck5N',
    'cS1yWciUaraTWGaveDf4jgwrJec9pD34EUzHBD6BL7jkGcCwRWo2',
    'cVLpBLgWqoJN55eHvaWnGC2jshRPESHHWm9dbfXRKf99dd6ZGSvw'
]

keys = []
for line in wifs:
    keys.append(wif_to_key(line))

for x in range(1, 10):
    keys[x].create_transaction([address, 0.0005, 'BTC'])
    time.sleep(5)

keys[0].create_transaction([address, 0.001, 'BTC'])
Пример #25
0
import web3
from bit import wif_to_key
from constants import *

command = './derive -g --mnemonic="black auto prosper select dust spirit multiply father until cabbage plastic crush" --cols=path,address,privkey,pubkey --format=json'

p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
output, err = p.communicate()
p_status = p.wait()

keys = json.loads(output)
print(keys)

pkey = keys[0]['privkey']
if pkey:
    print('success')

option = 0
while option != 0:
    option = int(input('''
        1. Get Blance in BTC
        2. Get Blance in USD
        3. Send Funds
        4. Close
        '''))
    pkey = keys[0]['privkey']
    key = wif_to_key(pkey)
    if option == 1:
        print(key.get_balance('btc'))
    elif option == 2:
        print(key.balance_as('usd'))
Пример #26
0
from bit import wif_to_key

key = wif_to_key("92jGVAFiSNJQdJH21qJYBzH9bsJMZ1Q6GiHqS1QNY6edh6Rn36g")

balance = key.get_balance("btc")

print(balance)
Пример #27
0
import json
from sqlalchemy import func, exc
from src.extensions import db
from src.main.models import Queue, Pool, User
import sys
from bit import wif_to_key
from blockcypher import simple_spend

priv = '---'  #removed for privacy
wallet = wif_to_key(priv)
recvaddress = ['', '']  #removed for privacy
key = ''  #removed for privacy
POOL_SIZE = 10
buyin = 0.0005
fees = 1


def get_count(q):
    count_q = q.statement.with_only_columns([func.count()]).order_by(None)
    count = q.session.execute(count_q).scalar()
    return count


def addtransaction(data):
    txaddresses = []
    bidValue = 0

    for txInput in data["inputs"]:
        txaddresses.append(txInput["addresses"])

    for output in data["outputs"]:
Пример #28
0
        from bit.network import NetworkAPI
        return NetworkAPI.broadcast_tx_testnet(signed)


# Send Transaction for BTC

## Fund the first address
funding_address = coins['btc-test'][0]['address']

## Set up the from account and the to address
btc_address_from = coins[BTCTEST][0]['privkey']
btc_address_to = coins[BTCTEST][1]['address']

## Initialize the send_tx
from bit import wif_to_key
key_1 = wif_to_key(btc_address_from)
key_2 = wif_to_key(coins[BTCTEST][1]['privkey'])

print(f'From Address Balance:{key_1.get_balance("btc")}')
print(f'To Address Balance:{key_2.get_balance("btc")}')

send_tx(BTCTEST, priv_key_to_account(BTCTEST, btc_address_from),
        btc_address_to, 0.0000001)

# Send Transaction for ETH

ethereum_network_address = coins['eth'][0]['address']

# Ethereum Test transaction

## To and From Addresses