I write crypto currency and i have this error while send transaction #129168
Unanswered
wojakos
asked this question in
Programming Help
Replies: 1 comment
-
reddit link (better) https://www.reddit.com/r/CodingHelp/comments/1dk6huc/i_write_crypto_currency_and_i_have_this/ |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Body
Wystąpił błąd podczas wysyłania transakcji: Invalid transaction signature
my_wallet.py
import os
import ecdsa
import requests
import json
import sqlite3
from ecdsa import SigningKey, SECP256k1
Kolory do konsoli
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
URL = 'http://localhost:5000'
def clear_console():
# Czyszczenie konsoli w zależności od systemu
os.system('cls' if os.name == 'nt' else 'clear')
def create_wallet():
clear_console()
print(f"{bcolors.OKBLUE}--- TWORZENIE NOWEGO PORTEFELA ---{bcolors.ENDC}")
# Generowanie kluczy na kliencie
private_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
public_key = private_key.get_verifying_key()
# Adres portfela
address = public_key.to_string().hex()
# Wyświetlenie klucza prywatnego (tylko w celach demonstracyjnych, nie przechowuj prywatnych kluczy w kodzie!)
print(f'{bcolors.OKGREEN}Klucz prywatny: {private_key.to_string().hex()}{bcolors.ENDC}')
# Zapis kluczy lokalnie
save_wallet_to_local_db(address, private_key.to_string().hex())
# Wysyłanie publicznego klucza do serwera
response = requests.post(
f'{URL}/wallet/create',
json={'public_key': public_key.to_string().hex(), 'address': address},
headers={'Content-Type': 'application/json'}
)
if response.status_code == 201:
print(f'{bcolors.OKGREEN}Nowy portfel został utworzony. Adres: {address}{bcolors.ENDC}')
else:
print(f'{bcolors.FAIL}Wystąpił błąd podczas tworzenia portfela.{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
def save_wallet_to_local_db(address, private_key):
conn = sqlite3.connect('local_wallets.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS wallets (address TEXT PRIMARY KEY, private_key TEXT)''')
cursor.execute('INSERT OR IGNORE INTO wallets (address, private_key) VALUES (?, ?)', (address, private_key))
conn.commit()
conn.close()
def load_wallet_from_local_db():
clear_console()
print(f"{bcolors.OKBLUE}--- LOGOWANIE DO PORTEFELA ---{bcolors.ENDC}")
conn = sqlite3.connect('local_wallets.db')
cursor = conn.cursor()
cursor.execute('SELECT address, private_key FROM wallets')
rows = cursor.fetchall()
conn.close()
if not rows:
print(f'{bcolors.WARNING}Brak zapisanych portfeli. Utwórz nowy portfel.{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
return None
print('Wybierz portfel do załadowania:')
for i, row in enumerate(rows, start=1):
print(f'{i}. {row[0]}')
try:
choice = int(input('Wybierz numer portfela: '))
if choice < 1 or choice > len(rows):
raise ValueError
except ValueError:
print(f'{bcolors.FAIL}Nieprawidłowy wybór.{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
return None
clear_console()
address, private_key = rows[choice - 1]
return address, private_key
def get_balance(address):
clear_console()
print(f"{bcolors.OKBLUE}--- SPRAWDZANIE SALDA ---{bcolors.ENDC}")
response = requests.get(f'{URL}/wallet/balance', params={'address': address})
if response.status_code == 200:
balance = response.json()['balance']
print(f'{bcolors.OKGREEN}Saldo portfela {address}: {balance}{bcolors.ENDC}')
else:
print(f'{bcolors.FAIL}Wystąpił błąd podczas pobierania salda.{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
def send_transaction(sender, recipient, amount, private_key):
clear_console()
print(f"{bcolors.OKBLUE}--- WYSYŁANIE TRANSAKCJI ---{bcolors.ENDC}")
transaction = {
'sender': sender,
'recipient': recipient,
'amount': amount
}
# Podpisanie transakcji
private_key_obj = SigningKey.from_string(bytes.fromhex(private_key), curve=SECP256k1)
transaction_data = json.dumps(transaction, sort_keys=True).encode()
signature = private_key_obj.sign(transaction_data).hex()
transaction['signature'] = signature
# Wysłanie transakcji do serwera wraz z kluczem prywatnym
try:
response = requests.post(
f'{URL}/transactions/new',
json=transaction,
headers={'Content-Type': 'application/json'}
)
if response.status_code == 201:
print(f'{bcolors.OKGREEN}Transakcja została dodana do bloku.{bcolors.ENDC}')
else:
print(f'{bcolors.FAIL}Wystąpił błąd podczas wysyłania transakcji: {response.text}{bcolors.ENDC}')
except requests.exceptions.RequestException as e:
print(f'{bcolors.FAIL}Wystąpił błąd podczas wysyłania transakcji: {e}{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
def menu():
while True:
clear_console()
print(f"{bcolors.HEADER}=== MENU GŁÓWNE ==={bcolors.ENDC}")
print('1. Stwórz nowy portfel')
print('2. Zaloguj się do istniejącego portfela')
print('3. Wyjście')
choice = input('Wybierz opcję: ')
if choice == '1':
create_wallet()
elif choice == '2':
wallet = load_wallet_from_local_db()
if wallet:
address, private_key = wallet
wallet_menu(address, private_key)
elif choice == '3':
break
else:
print(f'{bcolors.FAIL}Nieprawidłowy wybór.{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
def wallet_menu(address, private_key):
while True:
clear_console()
print(f"{bcolors.HEADER}=== MENU PORTELA ==={bcolors.ENDC}")
print('1. Sprawdź saldo')
print('2. Wyślij środki')
print('3. Wyloguj się')
choice = input('Wybierz opcję: ')
if choice == '1':
get_balance(address)
elif choice == '2':
recipient = input('Podaj adres odbiorcy: ')
amount = float(input('Podaj kwotę: '))
send_transaction(address, recipient, amount, private_key)
elif choice == '3':
break
else:
print(f'{bcolors.FAIL}Nieprawidłowy wybór.{bcolors.ENDC}')
input(f'{bcolors.OKBLUE}Naciśnij Enter, aby wrócić do menu głównego...{bcolors.ENDC}')
clear_console()
if name == 'main':
menu()
app.py
from flask import Flask, jsonify, request
from blockchain import Blockchain
from wallet import Wallet, save_wallet_to_db, load_wallet_from_db
app = Flask(name)
blockchain = Blockchain()
@app.route('/wallet/create', methods=['POST'])
def create_wallet():
values = request.get_json()
if not values or 'public_key' not in values or 'address' not in values:
return 'Public key and address are required', 400
public_key = values['public_key']
address = values['address']
save_wallet_to_db(address, public_key)
response = {
'message': 'New wallet created',
'address': address,
}
return jsonify(response), 201
@app.route('/wallet/balance', methods=['GET'])
def get_balance():
address = request.args.get('address')
if not address:
return 'Address parameter is required', 400
balance = blockchain.get_balance(address)
response = {
'address': address,
'balance': balance
}
return jsonify(response), 200
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json()
required = ['sender', 'recipient', 'amount', 'signature']
if not all(k in values for k in required):
return 'Missing values', 400
# Strip whitespace from signature
signature = values['signature'].strip().replace(' ', '')
values['signature'] = signature
is_valid = blockchain.verify_transaction(values)
if not is_valid:
return 'Invalid transaction signature', 400
try:
blockchain.add_transaction(values['sender'], values['recipient'], values['amount'], values['signature'])
response = {'message': 'Transaction will be added to a block'}
return jsonify(response), 201
except Exception as e:
return str(e), 400
@app.route('/mine', methods=['POST'])
def mine():
values = request.get_json()
miner_address = values.get('miner_address')
if not miner_address:
return 'Miner address is required', 400
new_block = blockchain.mine_block(miner_address)
response = {
'message': 'New block forged',
'block': {
'index': new_block.index,
'timestamp': new_block.timestamp,
'transactions': new_block.transactions,
'nonce': new_block.nonce,
'previous_hash': new_block.previous_hash,
'miner_address': new_block.miner_address
}
}
return jsonify(response), 200
@app.route('/chain', methods=['GET'])
def full_chain():
response = {
'chain': [block.dict for block in blockchain.chain],
'length': len(blockchain.chain),
}
return jsonify(response), 200
@app.route('/wallet/transactions', methods=['GET'])
def get_transactions_for_wallet():
address = request.args.get('address')
if not address:
return 'Address parameter is required', 400
transactions = blockchain.get_transactions_for_wallet(address)
response = {
'transactions': transactions,
}
return jsonify(response), 200
if name == 'main':
app.run(host='0.0.0.0', port=5000)
blockchain.py
import hashlib
import json
import time
import sqlite3
from ecdsa import VerifyingKey, SECP256k1, BadSignatureError # Import BadSignatureError explicitly
class Block:
def init(self, index, previous_hash, timestamp, transactions, nonce=0, miner_address=None):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.transactions = transactions
self.nonce = nonce
self.miner_address = miner_address
self.hash = self.calculate_hash()
def calculate_hash(self):
block_string = json.dumps(self.dict, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
class Blockchain:
def init(self):
self.chain = []
self.current_transactions = []
self.create_genesis_block()
self.load_chain_from_db()
def create_genesis_block(self):
conn = sqlite3.connect('blockchain.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS blocks
(block_index INTEGER PRIMARY KEY,
timestamp REAL,
previous_hash TEXT,
transactions TEXT,
nonce INTEGER,
hash TEXT,
miner_address TEXT)''')
cursor.execute('''SELECT COUNT(*) FROM blocks''')
if cursor.fetchone()[0] == 0:
genesis_block = Block(0, '0', time.time(), [])
self.chain.append(genesis_block)
self.save_block_to_db(genesis_block)
conn.close()
def add_block(self, block):
self.chain.append(block)
self.save_block_to_db(block)
def add_transaction(self, sender_address, recipient_address, amount, signature):
transaction = {
'sender': sender_address,
'recipient': recipient_address,
'amount': amount,
'signature': signature,
'timestamp': time.time()
}
# Weryfikacja transakcji
if self.verify_transaction(transaction):
self.current_transactions.append(transaction)
self.save_transaction_to_db(transaction)
return True
else:
return False
def mine_block(self, miner_address):
last_block = self.chain[-1]
index = last_block.index + 1
timestamp = time.time()
transactions = self.current_transactions
previous_hash = last_block.hash
nonce = self.proof_of_work(index, timestamp, transactions, previous_hash)
new_block = Block(index, previous_hash, timestamp, transactions, nonce, miner_address)
self.add_block(new_block)
self.update_wallet_balances(transactions)
self.update_wallet_balance(miner_address, 1) # Przyznanie 1 jednostki za wydobycie bloku
self.current_transactions = []
return new_block
def proof_of_work(self, index, timestamp, transactions, previous_hash):
nonce = 0
while not self.valid_proof(index, timestamp, transactions, previous_hash, nonce):
nonce += 1
return nonce
def valid_proof(self, index, timestamp, transactions, previous_hash, nonce):
block = Block(index, previous_hash, timestamp, transactions, nonce)
guess_hash = block.calculate_hash()
return guess_hash[:4] == "0000"
def get_balance(self, address):
conn = sqlite3.connect('wallets.db')
cursor = conn.cursor()
cursor.execute('SELECT balance FROM wallets WHERE address = ?', (address,))
result = cursor.fetchone()
balance = result[0] if result else 0
conn.close()
return balance
def update_wallet_balance(self, address, amount):
conn = sqlite3.connect('wallets.db')
cursor = conn.cursor()
cursor.execute('SELECT balance FROM wallets WHERE address = ?', (address,))
result = cursor.fetchone()
if result:
new_balance = result[0] + amount
cursor.execute('UPDATE wallets SET balance = ? WHERE address = ?', (new_balance, address))
else:
cursor.execute('INSERT INTO wallets (address, balance) VALUES (?, ?)', (address, amount))
conn.commit()
conn.close()
def update_wallet_balances(self, transactions):
for transaction in transactions:
sender = transaction['sender']
recipient = transaction['recipient']
amount = transaction['amount']
self.update_wallet_balance(sender, -amount)
self.update_wallet_balance(recipient, amount)
def save_block_to_db(self, block):
conn = sqlite3.connect('blockchain.db')
cursor = conn.cursor()
cursor.execute('''INSERT INTO blocks (block_index, timestamp, previous_hash, transactions, nonce, hash, miner_address)
VALUES (?, ?, ?, ?, ?, ?, ?)''',
(block.index, block.timestamp, block.previous_hash, json.dumps(block.transactions), block.nonce, block.hash, block.miner_address))
conn.commit()
conn.close()
def save_transaction_to_db(self, transaction):
conn = sqlite3.connect('blockchain.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS transactions
(transaction_id INTEGER PRIMARY KEY AUTOINCREMENT,
sender TEXT,
recipient TEXT,
amount REAL,
signature TEXT,
timestamp REAL)''')
cursor.execute('''INSERT INTO transactions (sender, recipient, amount, signature, timestamp)
VALUES (?, ?, ?, ?, ?)''',
(transaction['sender'], transaction['recipient'], transaction['amount'], transaction['signature'], transaction['timestamp']))
conn.commit()
conn.close()
def load_chain_from_db(self):
conn = sqlite3.connect('blockchain.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM blocks ORDER BY block_index')
rows = cursor.fetchall()
for row in rows:
transactions = json.loads(row[3])
loaded_block = Block(row[0], row[2], row[1], transactions, row[4], row[6])
loaded_block.hash = row[5]
self.chain.append(loaded_block)
conn.close()
def get_transactions_for_wallet(self, address):
conn = sqlite3.connect('blockchain.db')
cursor = conn.cursor()
cursor.execute('''SELECT * FROM transactions WHERE sender = ? OR recipient = ?''', (address, address))
rows = cursor.fetchall()
transactions = []
for row in rows:
transaction = {
'sender': row[1],
'recipient': row[2],
'amount': row[3],
'signature': row[4],
'timestamp': row[5]
}
transactions.append(transaction)
conn.close()
return transactions
def verify_transaction(self, transaction):
sender_public_key = VerifyingKey.from_string(bytes.fromhex(transaction['sender']), curve=SECP256k1)
transaction_data = json.dumps(transaction, sort_keys=True).encode()
transaction_hash = hashlib.sha256(transaction_data).hexdigest()
try:
return sender_public_key.verify(bytes.fromhex(transaction['signature']), transaction_hash.encode())
except BadSignatureError:
# Handle the case where the signature verification fails
return False # Or any appropriate action or logging
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions