import json
import sys
import time
import green_gdk as gdk
def main():
valid_environments = ['dev', 'test', 'amp']
environment = 'dev'
if len(sys.argv) > 1:
environment = sys.argv[1].lower()
if environment not in valid_environments:
print(f"Error: Invalid environment '{environment}'")
print(f"Valid environments are: {', '.join(valid_environments)}")
sys.exit(1)
print(f"Using environment: {environment}")
gdk.init({
'datadir': '.', 'log_level': 'warn'
})
mnemonics = {
'dev': "brick jump above ten cargo hobby forum deer remove curve lion embrace ecology trim increase purchase menu curve prosper blame blanket combine color pelican",
'test': "voice twelve rhythm cannon rebuild glove drift quiz spider rebuild cake eight abandon gauge frog animal cram peanut blossom pumpkin already scheme rookie physical",
'amp': "blanket awful machine pudding soft feature toe panel primary biology salon remove aspect creek thank true ridge milk right father drive economy gold filter"
}
mnemonic = mnemonics[environment]
if not gdk.validate_mnemonic(mnemonic):
raise Exception("Invalid mnemonic")
session = gdk.Session({'name': 'testnet-liquid'})
credentials = {'mnemonic': mnemonic}
def login_with_retry(session, credentials, max_retries=3):
for attempt in range(max_retries):
try:
try:
print("Attempting to login to existing wallet...")
session.login_user({}, credentials).resolve()
print("Successfully logged in to existing wallet")
return session
except RuntimeError as e:
if 'id_login_failed' in str(e):
print("Wallet doesn't exist, registering new wallet...")
session.register_user({}, credentials).resolve()
session.login_user({}, credentials).resolve()
print("Successfully registered and logged in")
return session
else:
raise
except RuntimeError as e:
if 'reconnect required' in str(e) and attempt < max_retries - 1:
print(f"Connection error, retrying... (attempt {attempt + 2}/{max_retries})")
time.sleep(2)
session = gdk.Session({'name': 'testnet-liquid'})
else:
raise
return session
session = login_with_retry(session, credentials)
subaccounts_result = session.get_subaccounts().resolve()
existing_subaccounts = {}
for subaccount in subaccounts_result['subaccounts']:
if subaccount.get('type', '') == '2of2':
existing_subaccounts[subaccount['name']] = subaccount
accounts = []
print("\nRetrieving first 20 2of2 subaccounts...")
all_2of2_accounts = []
for subaccount in subaccounts_result['subaccounts']:
if subaccount.get('type', '') == '2of2':
all_2of2_accounts.append(subaccount)
all_2of2_accounts.sort(key=lambda x: x['pointer'])
for i, subaccount in enumerate(all_2of2_accounts[:20], 1):
account_name = subaccount['name']
pointer = subaccount['pointer']
print(f" Processing subaccount {i:2d}: {account_name if account_name else f'2of2 Account (pointer: {pointer})'}")
subaccount_details = subaccount
address_details = None
try:
address_details = session.get_receive_address({'subaccount': pointer}).resolve()
address = address_details.get('address', 'N/A')
except Exception as e:
print(f" Warning: Could not get address for subaccount {i}: {e}")
address = 'N/A'
service_xpub = 'N/A'
script = 'N/A'
user_pubkey = 'N/A'
service_pubkey = 'N/A'
if address_details:
service_xpub = address_details.get('service_xpub', 'N/A')
script = address_details.get('script', 'N/A')
if script != 'N/A' and len(script) > 100:
try:
first_pubkey_start = 6 if script[first_pubkey_start:first_pubkey_start+2] == '21': user_pubkey = script[first_pubkey_start+2:first_pubkey_start+2+66]
second_21_pos = script.find('21', 80)
if second_21_pos != -1:
service_pubkey = script[second_21_pos+2:second_21_pos+2+66]
except Exception as e:
print(f" Warning: Could not parse script: {e}")
accounts.append({
'index': i,
'name': account_name if account_name else f'2of2 Account (pointer: {pointer})',
'pointer': pointer,
'address': address,
'user_pubkey': user_pubkey,
'service_pubkey': service_pubkey,
'service_xpub': service_xpub
})
print("\n" + "=" * 100)
print(f"2of2 Subaccounts with Addresses and Public Keys (Environment: {environment.upper()}):")
print("=" * 100)
for account in accounts:
print(f"{account['index']:2d}. {account['name']}")
print(f" Address: {account['address']}")
print(f" User PubKey: {account['user_pubkey']}")
print(f" Service PubKey: {account['service_pubkey']}")
print(f" Service XPub: {account['service_xpub']}")
print()
print("=" * 100)
print(f"Total subaccounts: {len(accounts)}")
print("=" * 100)
return accounts
if __name__ == "__main__":
try:
accounts = main()
print(f"\nSuccessfully processed {len(accounts)} subaccounts!")
except Exception as e:
print(f"\nError: {e}")
import traceback
traceback.print_exc()