I have created a wallet using bitcoinlib. The wallet is named 'my-awesome-wallet55.' When I try to open my existing wallet with a newly generated mnemonic phrase, the behavior I expect is an exception or security error, however the wallet opens anyway. I can manually check the private keys to create my own security check, but shouldn't trying to open an existing wallet with the wrong key fail? Seems like a pretty big security issue otherwise.
from bitcoinlib.wallets import Wallet, wallet_create_or_open
from bitcoinlib.keys import HDKey
from bitcoinlib.mnemonic import Mnemonic
# Creating a new Mnemonic phrase to try and open an existing wallet with
passphrase=Mnemonic().generate(strength=256, add_checksum=True)
# Use new phrase to create key
key = HDKey.from_passphrase(passphrase, witness_type='segwit', network='testnet')
# In my opinion this should fail because I provided the wrong key, but it returns the wallet
w = Wallet('my-awesome-wallet55', main_key_object=key)
# Statement showing that our private keys are different
print("key.private_hex: " + key.private_hex + "\nw.main_key.key_private.hex(): " +
w.main_key.key_private.hex())
if key.private_hex == w.main_key.key_private.hex():
# We don't make it here because our private keys don't match
print("Wallet 'my-awesome-wallet55' authenticated")
w.utxos_update()
print("Balance: " + str(w.balance()))
print("Wallet address: " + w.get_key().address)
w.info()
else:
# Instead we make it here and still have access to the wallet
print("Wallet Authentication failed")
w.utxos_update()
print("Balance: " + str(w.balance()))
print("Wallet address: " + w.get_key().address)
w.info()
Is there a standard way for authenticating a wallet using bitcoinlib? Based on what I have here, it seems someone only needs to know the name of a wallet to gain complete access over it.
UPDATE:
After getting Frank's question, I updated the code to try and send a transaction:
from bitcoinlib.wallets import Wallet, wallet_create_or_open
from bitcoinlib.keys import HDKey
from bitcoinlib.mnemonic import Mnemonic
passphrase=Mnemonic().generate(strength=256, add_checksum=True)
#passphrase='lumber romance negative child immense grab icon wasp silver essay enjoy jewel mom demise fit moral device hand capable toilet spirit age enforce deny'
print(passphrase)
key = HDKey.from_passphrase(passphrase, witness_type='segwit', network='testnet')
#wallet_create_or_open('my-awesome-wallet55', keys=passphrase, witness_type='segwit', network='testnet')
w = Wallet('my-awesome-wallet55', main_key_object=key)
print("key.private_hex: " + key.private_hex + "\nw.main_key.key_private.hex(): " + w.main_key.key_private.hex())
if key.private_hex == w.main_key.key_private.hex():
print("Wallet 'my-awesome-wallet55' authenticated")
w.utxos_update()
print("Balance: " + str(w.balance()))
t = w.send_to('tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec', 4000, fee=1000)
t.info()
else:
print("Wallet Authentication failed")
w.utxos_update()
print("Balance: " + str(w.balance()))
t = w.send_to('tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec', 4000, fee=1000)
t.info()
Here are the results:
Sonnys-MBP:TelegramBTCWallet sonnyparlin $ python test.py
unfold royal atom rule electric ice quote spin fiber quality lady just garment nature secret six garden comic carpet mom endless lamp family arctic
key.private_hex: 23ac38dc5293ee53918c8dfe18abc28975c8fa6963c876302aa4473ddca2f14a
w.main_key.key_private.hex(): 8c11283bf21e9344930ab9519742d6f59cd220528e0be17886d27a21c9c127c7
Wallet Authentication failed
Balance: 95000.0
Transaction 5e729021da81a5e6fc3b3d88b5bf136d09c78b0ac9a08be2cf1c90107e7ae27c
Date: None
Network: testnet
Version: 1
Witness type: segwit
Status: unconfirmed
Verified: True
Inputs
- tb1q7dx79l3maq2cqynpjzxqxsk3v6jhhaggzl07c3 0.00095000 tBTC badb9dbe2b4741310137de774e058aaf6cbba28e2f36c11640b241284f780f86 1
segwit sig_pubkey; sigs: 1 (1-of-1) valid
Outputs
- tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec 0.00004000 tBTC p2wpkh U
- tb1q9wg0vnqx63ng39s80gwqqffe2z7c5vvh0f4h3g 0.00090000 tBTC p2wpkh U
Size: 139
Vsize: 139
Fee: 1000
Confirmations: 0
Block: None
Pushed to network: True
Wallet: my-awesome-wallet55
I published this to the bitcoinlib developers as a bug, which they confirmed, you can follow it here:
https://github.com/1200wd/bitcoinlib/issues/206#issuecomment-991265402
Related
So i have this program which is a simple bank model and its lot of code but i have this issue wheret the input wont let the user input the others work fine but not this one
the problem
here is the code from server and client side
SERVER ---
if date_now.days <= 0:
c.send("huh".encode())
c.send("minimum day for fixed deposit is 1".encode())
else:
file6 = open(filename5, "r")
lines4 = file6.readlines()
file6.close()
line5 = lines4[line_number6 - 1].rstrip('\n')
c.send("The bank interest rate for fixed deposit account is 7% daily".encode())
c.send("please type 'yes' for confirmation".encode())
c.send("confirm: ".encode())
verify = c.recv(1024).decode()
Client ---
if to == "huh":
print(client.recv(1024).decode())
else:
print(client.recv(1024).decode())
print(client.recv(1024).decode())
msg = client.recv(1024).decode()
client.send(input(msg).encode())
lo = client.recv(1024).decode()
When I run the script, there are no errors but nothing gets printed nor logged, even if a model is actually uploaded.
import os
import requests
import sys
from colorama import Fore
os.system('cls')
while True:
info = requests.get("https://search.roblox.com/catalog/json?CatalogContect=2&Category=6&SortType=3&ResultsPerPage=1").json()
if info[0]['Name'] == "DreamGrim":
pass
elif info[0]['Name'] == ".gg/Fgj3VRGapz":
pass
else:
print(f"[{Fore.LIGHTGREEN_EX}+{Fore.RESET}] Logged model: " + str(info[0]['Name']) + " | " "https://www.roblox.com/library/" + str(info[0]['AssetId']) + "/" + str(info[0]['Name']))
with open('logs.txt', 'a') as f:
f.write(f"\n[+] Logged model: " + str(info[0]['Name']) + " | " "https://www.roblox.com/library/" + str(info[0]['AssetId']) + "/" + str(info[0]['Name']))
How do I make this work without the logs getting looped?
If I put it inside the while True: loop the logs start to loop and something like this happens:
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
[+] Logged model: Hot Chocolate | https://www.roblox.com/library/7881318998/Hot Chocolate
You have to terminate the while loop before the script can progress to the next step. If you try and run the following code you will get repeated 1s and no 2s:
while True:
print(1)
print(2)
A better way of structuring the code would be to get the info first and then iterate through it:
info = requests.get("https://search.roblox.com/catalog/json?CatalogContect=2&Category=6&SortType=3&ResultsPerPage=1").json()
for result in info:
if result['Name'] == "DreamGrim":
pass
...
You want to use the while True statement for something that should loop until you reach a point. Here, you are only creating and changing your variable's value over and over again.
You never break off of the loop so you never get to the rest of the code.
Maybe you wanted to use the with statement ?
Writing a python script that sets up pickup games. srv.connect() will time out if the IP/RCON are put in wrong and/or the server is down altogether. I do not want the discord bot to crash just because a server is down so I am trying to use a try/except to keep the bot going. A person can start a pickup by typing !pickup size 4 servername ... and if srv.connect() can not get a handshake with the server, itll time out and send a message in discord saying it can not find the server. Then they could do !pickup size 4 servername2 and itll work. Problem right now is that after doing !pickup size 4 servername it seems stuck on saying the rcon/ip is down even though servername2 should be running just fine. Any help?
if(message.content.startswith('!pickup size')):
if(pickupActive == 0):
x = message.content.split()
if(len(x) >= 4):
pServer = x[3]
if(pServer in servers):
srv = Console(host=servers[pServer][0], port= servers[pServer][1], password=servers[pServer][2])
try:
srv.connect()
servercfg = srv.execute("servercfgfile")
#print(servers[pServer][3])
if (servers[pServer][3] in servercfg): #and (pickupActive == 0)): #change "server.cfg" to whatever your server configurtion filename is for pickup play. keep the quotations
totalPlayers = [" "] * int(x[2])
initialPlayerCount = len(totalPlayers)
pickupLeader = message.author.name
totalPlayers.insert(playerCount, pickupLeader)
totalPlayers.remove(" ")
PopulateTable()
await message.channel.send("```Pickup Game Starting! " + pickupLeader + " is the leader for the Pickup Game! Come join in! type '!pickup add' to join```")
await message.channel.send("```" + msg + "```")
pickupActive = 1
else:
await message.channel.send("`" + servers[pServer][4] + "`")
except:
await message.channel.send("Can not connect to the server for rcon..")
srv.disconnect()
else:
await message.channel.send("`Please specify the size of the pickup and a valid server name..`")
else:
await message.channel.send("`Proper formatting not used, please say !pickup size # server (Example: !pickup size 3 nwo)`")
else:
await message.channel.send("`Already a pickup game in progress, please add up to the current pickup game..`")
I'm writing a program to toggle the lights at my house based on my iPhone's GPS coordinates. Below is what I have so far. However, I feel like there must be a better way to do this. Is there a way to get GPS data without pinging my phone every five minutes?
So far I've tried the following with no joy:
Using Shortcuts and Scriptable I tried to write some JavaScript that would trigger when I got close to home. However, I could not figure out how to use await require('wemo-client') using scriptablify. I kept getting an error, "ReferenceError: Can't find variable: require".
IFTTT does not have a variable timed trigger so the lights won't turn off after 15 minutes. Also, I plan on adding a motion sensor trigger that is unsupported.
Pythonista is $10. Yes, I am that cheap.
Apple HomeKit does not support the model I'm using, Wemo Smart Light Switch F7C030.
The code below works, but I hate that I have to ping my phone every five minutes. I'd rather save battery life by firing this code once or twice a day, as needed.
Any suggestions would be greatly appreciated.
Code:
import sys
import time
import datetime
import os
from pyicloud import PyiCloudService
import pywemo
APPLE_ID = os.getenv('APPLE_ID') # Apple ID username
APPLE_ID_PASSWORD = os.getenv('APPLE_ID_PASSWORD') # Apple ID password
API = PyiCloudService(APPLE_ID, APPLE_ID_PASSWORD)
IPHONE = API.devices[1]
LOCATION = IPHONE.location()
FIVE = 300 # 5 * 60 seconds
FIFTEEN = 900 # 15 * 60 seconds
ONEMILE = 0.01449275362318840579710144927536 # one mile is 1/69 degrees lat or long
HOMELAT = # my home's latitude
HOMELONG = # my home's longitude
WEMOS = pywemo.discover_devices()
LEN_WEMOS = range(len(WEMOS))
# Two factor authentication to retrieve iPhone data
if API.requires_2fa:
import click
print("Two-step authentication required. Your trusted devices are:")
DEVICES = API.devices
for i, device in enumerate(DEVICES):
print(" %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber'))))
DEF_DEVICE = click.prompt('Which device would you like to use?', default=0)
DEVICE = DEVICES[DEF_DEVICE]
if not API.send_verification_code(DEVICE):
print("Failed to send verification code")
sys.exit(1)
CODE = click.prompt('Please enter validation code')
if not API.validate_verification_code(DEVICE, CODE):
print("Failed to verify verification code")
sys.exit(1)
# Turn off the lights when I leave
def leavehome():
timenow = datetime.datetime.now()
print("Left home on {}".format(timenow.strftime("%B %d, %Y at %H:%M:%S")))
for wemo in LEN_WEMOS:
WEMOS[wemo].off()
# Turn on the lights for 15 minutes when I get home
def arrivehome():
timenow = datetime.datetime.now()
print("Arrived home on {}".format(timenow.strftime("%B %d, %Y at %H:%M:%S")))
# Loop through all Wemo devices
for wemo in LEN_WEMOS:
WEMOS[wemo].on()
time.sleep(FIFTEEN)
for wemo in LEN_WEMOS:
WEMOS[wemo].off()
# Automatically turn off the lights after 15 minutes - save electricity
def timeoff():
time.sleep(FIFTEEN)
for wemo in LEN_WEMOS:
WEMOS[wemo].off()
# Ping my phone for GPS data
def pingphone(prev):
mylat = LOCATION["latitude"]
mylong = LOCATION["longitude"]
logic(prev, mylat, mylong)
time.sleep(FIVE)
# Perform logic to determine if I'm home, out, arriving, or leaving
def logic(prev, lat, long):
inrange = (HOMELAT+ONEMILE >= lat >= HOMELAT-ONEMILE and HOMELONG+ONEMILE >= long >= HOMELONG-ONEMILE)
current = bool(inrange)
previous = prev
if current and not previous:
arrivehome()
elif previous and not current:
leavehome()
else:
timeoff()
pingphone(current)
# Run the script
pingphone(False)
I'm trying to install CDH5 parcels on Hadoop-cluster using Cloudera Manager Python API. I'm doing this using following code:
test_cluster = ... # configuring cluster
# adding hosts ...
for parcel in test_cluster.get_all_parcels():
if parcel.product == 'CDH' and 'cdh5':
parcel.start_download().wait()
parcel.start_distribution().wait()
success = parcel.activate().wait().success
But I catch such error:
cm_api.api_client.ApiException: Parcel for CDH : 5.8.0-1.cdh5.8.0.p0.42 is not available on UBUNTU_TRUSTY. (error 400)
The CDH 5.8.0-1.cdh5.8.0.p0.42 was in AVAILABLE_REMOTELY, as we can see if print a string representation on this parcel:
<ApiParcel>: CDH-5.8.0-1.cdh5.8.0.p0.42 (stage: AVAILABLE_REMOTELY) (state: None) (cluster: TestCluster)
After the execution of code, parcel changes its stage to DOWNLOADED.
It seems, I should add a new parcel repository, compatible with Ubuntu Trusty (14.04). But I don't know of doing this using Cloudera Manager API.
How I can specify the new repository for installing correct CDH?
You may want to be more specific about the parcel you are acting on. I use something like this for the same purpose, the important part for your question is the combined check on parcel.version and parcel.product. After that (yes I am verbose in my output) I print the list of parcels to verify I am trying to only install the 1 parcel I want.
I'm sure you've been here, but if not the cm_api github site has some helpful examples too.
cdh_version = "CDH5"
cdh_version_number = "5.6.0"
# CREATE THE LIST OF PARCELS TO BE INSTALLED (CDH)
parcels_list = []
for parcel in cluster.get_all_parcels():
if parcel.version.startswith(cdh_version_number) and parcel.product == "CDH":
parcels_list.append(parcel)
for parcel in parcels_list:
print "WILL INSTALL " + parcel.product + ' ' + parcel.version
# DISTRIBUTE THE PARCELS
print "DISTRIBUTING PARCELS..."
for p in parcels_list:
cmd = p.start_distribution()
if not cmd.success:
print "PARCEL DISTRIBUTION FAILED"
exit(1)
# MAKE SURE THE DISTRIBUTION FINISHES
for p in parcels_list:
while p.stage != "DISTRIBUTED":
sleep(5)
p = get_parcel(api, p.product, p.version, cluster_name)
print p.product + ' ' + p.version + " DISTRIBUTED"
# ACTIVATE THE PARCELS
for p in parcels_list:
cmd = p.activate()
if not cmd.success:
print "PARCEL ACTIVATION FAILED"
exit(1)
# MAKE SURE THE ACTIVATION FINISHES
for p in parcels_list:
while p.stage != "ACTIVATED":
p = get_parcel(api, p.product, p.version, cluster_name)
print p.product + ' ' + p.version + " ACTIVATED"