A python script for colored bitcoin blockchain management


SUBMITTED BY: Guest

DATE: Nov. 21, 2012, 7:10 a.m.

FORMAT: Python

SIZE: 25.5 kB

HITS: 1362

  1. #!/usr/bin/env python
  2. """
  3. bitpaint.py
  4. ~~~~~~~~~~~
  5. Simple command-line utility to use the Bitcoin blockchain to track and manage so-called "colored coins", or "smart contracts/securities".
  6. Caution:
  7. - Private keys are stored in plaintext in your configuration file
  8. - Colored coin tracking is implemented following the "output
  9. ordering" method, but with very few test cases available,
  10. it is currently difficult to say whether or not the approach is
  11. compatible with approaches implemented elsewhere.
  12. - Remember to include a transaction fee when transferring assets,
  13. so that the transaction will confirm.
  14. (https://bitcointalk.org/index.php?topic=117630.0;all)
  15. Donations welcome: 1GsnaaAWYMb7yPwBQ19bSLLMTtsfSyjqg3
  16. """
  17. # Import libraries
  18. import jsonrpc
  19. from optparse import OptionParser
  20. import urllib2, ConfigParser, ctypes, ctypes.util, hashlib, simplejson as json, os, sys, binascii, collections
  21. jsonrpc.dumps = json.dumps
  22. ### Start: Generic helpers
  23. def JSONtoAmount(value):
  24. return long(round(value * 1e8))
  25. def AmountToJSON(amount):
  26. return float(amount / 1e8)
  27. ### End: Generic helpers
  28. ### Start: Create/Read Config
  29. # Here we create a configuration file if one does not exist already.
  30. # User is asked for details about his bitcoind so the script can connect.
  31. config_file = "bitpaint.conf"
  32. basic_bitpaint_conf = """[bitcoind]
  33. rpchost = %s
  34. rpcport = %s
  35. rpcuser = %s
  36. rpcpwd = %s
  37. [HoldingAddresses]
  38. addresses =
  39. private_keys =
  40. """
  41. # If the config file does not exists, ask user for details and write one
  42. if not os.path.exists(config_file):
  43. print "Configuration file bitpaint.conf not found. Creating one..."
  44. host = raw_input("bitcoind rpc host (default: 127.0.0.1): ")
  45. if len(host) == 0: host = "127.0.0.1"
  46. port = raw_input("bitcoind rpc port (default: 8332): ")
  47. if len(port) == 0: port = "8332"
  48. user = raw_input("bitcoind rpc username (default: <blank>): ")
  49. pwd = raw_input("bitcoind rpc password (default: <blank>): ")
  50. f = open(config_file, 'w')
  51. f.write(basic_bitpaint_conf % (host,port,user,pwd))
  52. f.close()
  53. # Parse the config file
  54. reserved_sections = ['bitcoind', 'HoldingAddresses']
  55. config = ConfigParser.ConfigParser()
  56. config.read(config_file)
  57. rpchost = config.get('bitcoind', 'rpchost')
  58. rpcport = config.get('bitcoind', 'rpcport')
  59. rpcuser = config.get('bitcoind', 'rpcuser')
  60. rpcpwd = config.get('bitcoind', 'rpcpwd')
  61. # Connect to bitcoind
  62. if len(rpcuser) == 0 and len(rpcpwd) == 0:
  63. bitcoind_connection_string = "http://s:%s" % (rpchost,rpcport)
  64. else:
  65. bitcoind_connection_string = "http://%s:%s@%s:%s" % (rpcuser,rpcpwd,rpchost,rpcport)
  66. sp = jsonrpc.ServiceProxy(bitcoind_connection_string)
  67. ### End: Create/Read Config
  68. ### Start: Address Generation code
  69. # The following code was yoinked from addrgen.py
  70. # Thanks to: Joric/bitcoin-dev, june 2012, public domain
  71. ssl = ctypes.cdll.LoadLibrary (ctypes.util.find_library ('ssl') or 'libeay32')
  72. def check_result (val, func, args):
  73. if val == 0: raise ValueError
  74. else: return ctypes.c_void_p (val)
  75. ssl.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p
  76. ssl.EC_KEY_new_by_curve_name.errcheck = check_result
  77. class KEY:
  78. def __init__(self):
  79. NID_secp256k1 = 714
  80. self.k = ssl.EC_KEY_new_by_curve_name(NID_secp256k1)
  81. self.compressed = False
  82. self.POINT_CONVERSION_COMPRESSED = 2
  83. self.POINT_CONVERSION_UNCOMPRESSED = 4
  84. def __del__(self):
  85. if ssl:
  86. ssl.EC_KEY_free(self.k)
  87. self.k = None
  88. def generate(self, secret=None):
  89. if secret:
  90. self.prikey = secret
  91. priv_key = ssl.BN_bin2bn(secret, 32, ssl.BN_new())
  92. group = ssl.EC_KEY_get0_group(self.k)
  93. pub_key = ssl.EC_POINT_new(group)
  94. ctx = ssl.BN_CTX_new()
  95. ssl.EC_POINT_mul(group, pub_key, priv_key, None, None, ctx)
  96. ssl.EC_KEY_set_private_key(self.k, priv_key)
  97. ssl.EC_KEY_set_public_key(self.k, pub_key)
  98. ssl.EC_POINT_free(pub_key)
  99. ssl.BN_CTX_free(ctx)
  100. return self.k
  101. else:
  102. return ssl.EC_KEY_generate_key(self.k)
  103. def get_pubkey(self):
  104. size = ssl.i2o_ECPublicKey(self.k, 0)
  105. mb = ctypes.create_string_buffer(size)
  106. ssl.i2o_ECPublicKey(self.k, ctypes.byref(ctypes.pointer(mb)))
  107. return mb.raw
  108. def get_secret(self):
  109. bn = ssl.EC_KEY_get0_private_key(self.k);
  110. bytes = (ssl.BN_num_bits(bn) + 7) / 8
  111. mb = ctypes.create_string_buffer(bytes)
  112. n = ssl.BN_bn2bin(bn, mb);
  113. return mb.raw.rjust(32, chr(0))
  114. def set_compressed(self, compressed):
  115. self.compressed = compressed
  116. if compressed:
  117. form = self.POINT_CONVERSION_COMPRESSED
  118. else:
  119. form = self.POINT_CONVERSION_UNCOMPRESSED
  120. ssl.EC_KEY_set_conv_form(self.k, form)
  121. def dhash(s):
  122. return hashlib.sha256(hashlib.sha256(s).digest()).digest()
  123. def rhash(s):
  124. h1 = hashlib.new('ripemd160')
  125. h1.update(hashlib.sha256(s).digest())
  126. return h1.digest()
  127. b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  128. def base58_encode(n):
  129. l = []
  130. while n > 0:
  131. n, r = divmod(n, 58)
  132. l.insert(0,(b58_digits[r]))
  133. return ''.join(l)
  134. def base58_decode(s):
  135. n = 0
  136. for ch in s:
  137. n *= 58
  138. digit = b58_digits.index(ch)
  139. n += digit
  140. return n
  141. def base58_encode_padded(s):
  142. res = base58_encode(int('0x' + s.encode('hex'), 16))
  143. pad = 0
  144. for c in s:
  145. if c == chr(0):
  146. pad += 1
  147. else:
  148. break
  149. return b58_digits[0] * pad + res
  150. def base58_decode_padded(s):
  151. pad = 0
  152. for c in s:
  153. if c == b58_digits[0]:
  154. pad += 1
  155. else:
  156. break
  157. h = '%x' % base58_decode(s)
  158. if len(h) % 2:
  159. h = '0' + h
  160. res = h.decode('hex')
  161. return chr(0) * pad + res
  162. def base58_check_encode(s, version=0):
  163. vs = chr(version) + s
  164. check = dhash(vs)[:4]
  165. return base58_encode_padded(vs + check)
  166. def base58_check_decode(s, version=0):
  167. k = base58_decode_padded(s)
  168. v0, data, check0 = k[0], k[1:-4], k[-4:]
  169. check1 = dhash(v0 + data)[:4]
  170. if check0 != check1:
  171. raise BaseException('checksum error')
  172. if version != ord(v0):
  173. raise BaseException('version mismatch')
  174. return data
  175. def gen_eckey(passphrase=None, secret=None, pkey=None, compressed=False, rounds=1):
  176. k = KEY()
  177. if passphrase:
  178. secret = passphrase.encode('utf8')
  179. for i in xrange(rounds):
  180. secret = hashlib.sha256(secret).digest()
  181. if pkey:
  182. secret = base58_check_decode(pkey, 128)
  183. compressed = len(secret) == 33
  184. secret = secret[0:32]
  185. k.generate(secret)
  186. k.set_compressed(compressed)
  187. return k
  188. def get_addr(k):
  189. pubkey = k.get_pubkey()
  190. secret = k.get_secret()
  191. hash160 = rhash(pubkey)
  192. addr = base58_check_encode(hash160)
  193. payload = secret
  194. if k.compressed:
  195. payload = secret + chr(0)
  196. pkey = base58_check_encode(payload, 128)
  197. return addr, pkey
  198. ### End: Address Generation code
  199. ### Start: Transaction code
  200. def bc_address_to_hash_160(addr):
  201. bytes = b58decode(addr, 25)
  202. return bytes[1:21]
  203. __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  204. __b58base = len(__b58chars)
  205. def b58decode(v, length):
  206. """ decode v into a string of len bytes
  207. """
  208. long_value = 0L
  209. for (i, c) in enumerate(v[::-1]):
  210. long_value += __b58chars.find(c) * (__b58base**i)
  211. result = ''
  212. while long_value >= 256:
  213. div, mod = divmod(long_value, 256)
  214. result = chr(mod) + result
  215. long_value = div
  216. result = chr(long_value) + result
  217. nPad = 0
  218. for c in v:
  219. if c == __b58chars[0]: nPad += 1
  220. else: break
  221. result = chr(0)*nPad + result
  222. if length is not None and len(result) != length:
  223. return None
  224. return result
  225. def makek():
  226. # Create a dictionary with address as key and private-key
  227. # as value
  228. a = config.get('HoldingAddresses', 'addresses').split("+")
  229. p = config.get('HoldingAddresses', 'private_keys').split("+")
  230. k = {}
  231. for a in zip(a,p):
  232. k[a[0]] = a[1]
  233. return k
  234. def maketx(inputs, outputs, send=False):
  235. # Create a transaction, sign it - possibly send it - but
  236. # in either case return the raw hex
  237. # inputs: [('a7813e20045b2f2caf612c589adc7e985029167106a300b6a7157084c26967f5', 1, '1PPgZP53BrcG7hyXdWT9fugewmxL1H8LS3'),...]
  238. # outputs: [('1KRavVCsvaLi7ZzktHSCE3hPUvhPDhQKhz', 8000000),...]
  239. ip = []
  240. for txid,vout,_ in inputs:
  241. ip.append({"txid": txid, "vout": vout})
  242. op = collections.OrderedDict()
  243. for addr,amnt in outputs:
  244. op[addr] = AmountToJSON(amnt)
  245. tx = sp.createrawtransaction(ip,op)
  246. k = makek()
  247. ip = []
  248. pkeys = []
  249. for txid,vout,addr in inputs:
  250. ip.append({"txid": txid, "vout": vout, "scriptPubKey": '76a914'+bc_address_to_hash_160(addr).encode('hex')+'88ac'})
  251. if addr in k:
  252. pkeys.append(k[addr])
  253. else:
  254. pkeys.append(sp.dumpprivkey(addr))
  255. final_t = sp.signrawtransaction(tx,ip,pkeys)
  256. if send:
  257. sp.sendrawtransaction(tx)
  258. else:
  259. print final_t['hex']
  260. return final_t['hex']
  261. ### End: Transaction code
  262. ### Start: Blockchain Inspection/Traversion code
  263. def translate_bctx_to_bitcoindtx(tx_bc):
  264. tx = {}
  265. tx['locktime'] = 0
  266. tx['txid'] = tx_bc['hash']
  267. tx['version'] = tx_bc['ver']
  268. tx['vin'] = []
  269. tx['vout'] = []
  270. for i in tx_bc['inputs']:
  271. v = {}
  272. v['scriptSig'] = {'asm': '', 'hex': ''}
  273. v['sequence'] = 4294967295
  274. v['txid'] = json.loads(urllib2.urlopen("http://blockchain.info/rawtx/%s" % (i['prev_out']['tx_index'],)).read())['hash']
  275. v['vout'] = i['prev_out']['n']
  276. tx['vin'].append(v)
  277. for i in range(len(tx_bc['out'])):
  278. o = tx_bc['out'][i]
  279. v = {}
  280. v['n'] = i
  281. v['scriptPubKey'] = {}
  282. v['scriptPubKey']['addresses'] = [o['addr']]
  283. v['scriptPubKey']['asm'] = []
  284. v['scriptPubKey']['hex'] = []
  285. v['scriptPubKey']['reqSigs'] = 1,
  286. v['scriptPubKey']['type'] = 'pubkeyhash'
  287. v['value'] = float(o['value'])/1e8
  288. tx['vout'].append(v)
  289. return tx
  290. def gettx(txid):
  291. # Get the information of a single transaction, using
  292. # the bitcoind API
  293. try:
  294. tx_raw = sp.getrawtransaction(txid)
  295. tx = sp.decoderawtransaction(tx_raw)
  296. except:
  297. print "Error getting transaction "+txid+" details from bitcoind, trying blockchain.info"
  298. print "http://blockchain.info/rawtx/%s" % (txid,)
  299. tx_bc = json.loads(urllib2.urlopen("http://blockchain.info/rawtx/%s" % (txid,)).read())
  300. tx = translate_bctx_to_bitcoindtx(tx_bc)
  301. return tx
  302. def getaddresstxs(address):
  303. # Get all transactions associated with an address.
  304. # Uses blockchain.info to get this, bitcoind API
  305. # apparently has no equivalent function.
  306. address_info = json.loads(urllib2.urlopen("http://blockchain.info/address/%s?format=json"%(address,) ).read())
  307. tx_list = []
  308. for tx in address_info['txs']:
  309. tx_list.append(tx['hash'])
  310. return tx_list
  311. def getholderschange(txid):
  312. # Get a list of the new holders and old holders represented by a
  313. # single transaction, given as the tx-id.
  314. tid = txid.split(":")
  315. tx = gettx(tid[0])
  316. new_holders = []
  317. old_holders = []
  318. for i in tx['vin']:
  319. old_holders.append(i['txid']+":"+str(i['vout']))
  320. for o in tx['vout']:
  321. new_holders.append((o['scriptPubKey']['addresses'][0], o['value']))
  322. return new_holders, old_holders
  323. def spentby(tx_out):
  324. # Return the id of the transaction which spent the given txid/#
  325. # if single_input is true, it only returns if the tx_out was used as a single
  326. # input to the transaction.
  327. # This is because it is not possible to follow a colored coin across a transaction
  328. # with multiple inputs
  329. tid = tx_out.split(":")
  330. tx = gettx(tid[0])
  331. address = tx['vout'][int(tid[1])]['scriptPubKey']['addresses'][0]
  332. tx_list = getaddresstxs(address)
  333. for t in tx_list:
  334. outputs,inputs = getholderschange(t)
  335. for i in inputs:
  336. if i == tx_out:
  337. return t
  338. return None
  339. def match_outputs_to_inputs(input_values, output_values):
  340. output_belongs_to_input = [-1]*len(output_values)
  341. current_color_number = -1
  342. current_color_total = 0.0
  343. current_color_max = -1
  344. for i in range(len(output_values)):
  345. output_value = output_values[i]
  346. while current_color_total+output_value > current_color_max:
  347. current_color_number += 1
  348. current_color_total = 0.0
  349. if current_color_number >= len(input_values): return output_belongs_to_input
  350. current_color_max = input_values[current_color_number]
  351. output_belongs_to_input[i] = current_color_number
  352. current_color_total += output_value
  353. return output_belongs_to_input
  354. def get_relevant_outputs(tx_data,prevout_txid):
  355. global lost_track
  356. relevant_outputs = []
  357. input_values = []
  358. output_values = []
  359. input_colors = [-1]*len(tx_data['vin'])
  360. for pon in range(len(tx_data['vin'])):
  361. po = tx_data['vin'][pon]
  362. p_tid = po['txid']+":"+str(po['vout'])
  363. if p_tid == prevout_txid:
  364. input_colors[pon] = 0
  365. po_data = gettx(po['txid'])
  366. input_values.append(po_data['vout'][po['vout']]['value'])
  367. for pon in range(len(tx_data['vin'])):
  368. p_tid = po['txid']+":"+str(po['vout'])
  369. if p_tid in lost_track:
  370. po_data = gettx(po['txid'])
  371. input_values[input_colors.index(0)] += po_data['vout'][po['vout']]['value']
  372. input_values[pon] = 0
  373. lost_track.remove(p_tid)
  374. for o in tx_data['vout']:
  375. output_values.append(o['value'])
  376. output_colors = match_outputs_to_inputs(input_values, output_values)
  377. for o in range(len(output_colors)):
  378. if output_colors[o] == 0:
  379. relevant_outputs.append(tx_data['txid']+":"+str(o))
  380. return relevant_outputs
  381. def rec(prevout_txid, root_tx):
  382. holder_list = []
  383. spent_by = spentby(prevout_txid)
  384. txid,n = prevout_txid.split(":")
  385. if spent_by is None:
  386. tx_data = gettx(txid)
  387. o = tx_data['vout'][int(n)]
  388. holder_list.append((o['scriptPubKey']['addresses'][0],o['value'],prevout_txid))
  389. return holder_list
  390. tx_data = gettx(spent_by)
  391. relevant_outputs = get_relevant_outputs(tx_data,prevout_txid)
  392. if len(relevant_outputs) == 0:
  393. lost_track.append(spent_by)
  394. for ro in relevant_outputs:
  395. hl = rec(ro,root_tx)
  396. for h in hl:
  397. holder_list.append(h)
  398. return holder_list
  399. lost_track = []
  400. def get_current_holders(root_tx_out):
  401. # Get the current holders of the "colored coin" with
  402. # the given root (a string with txid+":"+n_output)
  403. global lost_track
  404. lost_track = []
  405. return rec(root_tx_out,root_tx_out)
  406. def get_unspent(addr):
  407. # Get the unspent transactions for an address
  408. # * Following section is disabled because blockchain.info has a bug that
  409. # returns the wrong transaction IDs.
  410. #d = json.loads(urllib2.urlopen('http://blockchain.info/unspent?address=%s' % addr).read())
  411. #return d
  412. # * Start of blockchain.info bug workaround:
  413. txs = getaddresstxs(addr)
  414. received = []
  415. sent = []
  416. for txid in txs:
  417. tx = gettx(txid)
  418. for i in tx['vin']:
  419. prev_out = gettx(i['txid'])
  420. for po in prev_out['vout']:
  421. n = po['n']
  422. po = po['scriptPubKey']
  423. if po['type'] == 'pubkeyhash':
  424. if po['addresses'][0] == addr:
  425. sent.append(i['txid']+":"+str(n))
  426. for o in tx['vout']:
  427. n = o['n']
  428. o = o['scriptPubKey']
  429. if o['type'] == 'pubkeyhash':
  430. if o['addresses'][0] == addr:
  431. received.append(txid+":"+str(n))
  432. unspent = []
  433. for r in received:
  434. if r not in sent:
  435. d = {}
  436. txid,n = r.split(":")
  437. d['tx_hash'] = txid
  438. d['tx_output_n'] = int(n)
  439. d['value'] = int(1e8*gettx(txid)['vout'][int(n)]['value'])
  440. unspent.append(d)
  441. return unspent
  442. # * End of blockchain.info bug workaround
  443. def get_non_asset_funds(addr):
  444. unspent = get_unspent(addr)
  445. asset_txids = []
  446. for s in config.sections():
  447. if s in reserved_sections: continue
  448. for txid in config.get(s, 'txid').split("+"):
  449. asset_txids.append(txid)
  450. naf = []
  451. for u in unspent:
  452. txid = u['tx_hash']+":"+str(u['tx_output_n'])
  453. if not txid in asset_txids:
  454. naf.append(u)
  455. return naf
  456. ### End: Blockchain Inspection/Traversion code
  457. ### Start: "User-facing" methods
  458. def generate_holding_address():
  459. # Generate an address, add it to the config file
  460. addr, pkey = get_addr(gen_eckey())
  461. addresses = config.get('HoldingAddresses', 'addresses')
  462. private_keys = config.get('HoldingAddresses', 'private_keys')
  463. if len(addresses) > 5:
  464. config.set('HoldingAddresses', 'addresses', '+'.join([addresses,addr]))
  465. config.set('HoldingAddresses', 'private_keys', '+'.join([private_keys,pkey]))
  466. else:
  467. config.set('HoldingAddresses', 'addresses', addr)
  468. config.set('HoldingAddresses', 'private_keys', pkey)
  469. config.write(open(config_file,'w'))
  470. return "Address added: "+addr
  471. def update_tracked_coins(name):
  472. # Update the list of owners of a tracked coin
  473. # and write to the config file
  474. root_tx = config.get(name, "root_tx")
  475. current_holders = get_current_holders(root_tx)
  476. holding_addresses = ""
  477. holding_amounts = ""
  478. holding_txids = ""
  479. total = 0.0
  480. for h in current_holders:
  481. holding_addresses += "+" + h[0]
  482. holding_amounts += "+" + str(h[1])
  483. holding_txids += "+" + h[2]
  484. config.set(name, "holders", holding_addresses[1:])
  485. config.set(name, "amounts", holding_amounts[1:])
  486. config.set(name, "txid", holding_txids[1:])
  487. config.write(open(config_file,'w'))
  488. def start_tracking_coins(name,txid):
  489. # Give a name of a tracked coin, together with a
  490. # root output that will be used to track it.
  491. # Write this to the config file, and update the
  492. # list of owners.
  493. if name in config.sections():
  494. return name+" already exists."
  495. config.add_section(name)
  496. config.set(name, "root_tx", txid)
  497. config.set(name, "holders", "")
  498. config.set(name, "amounts", "")
  499. config.set(name, "txid", "")
  500. config.write(open(config_file,'w'))
  501. update_tracked_coins(name)
  502. def show_holders(name):
  503. holders = config.get(name, "holders").split("+")
  504. amounts = config.get(name, "amounts").split("+")
  505. txids = config.get(name,"txid").split("+")
  506. total = 0.0
  507. print "*** %s ***" % (name,)
  508. for h in zip(holders,amounts,txids):
  509. print h[0],h[1],h[2]
  510. total += float(h[1])
  511. print "** Total %s: %f **" % (name,total)
  512. def show_my_holdings():
  513. sections = config.sections()
  514. my_holding_addresses = config.get('HoldingAddresses', 'addresses').split("+")
  515. for s in sections:
  516. if s in reserved_sections: continue
  517. holders = config.get(s, "holders").split("+")
  518. amounts = config.get(s, "amounts").split("+")
  519. txids = config.get(s, "txid").split("+")
  520. for h in holders:
  521. if h in my_holding_addresses:
  522. total_dividends = 0.0
  523. for naf in get_non_asset_funds(h):
  524. total_dividends += float(naf['value'])/1e8
  525. print s,amounts[holders.index(h)],"( div:",total_dividends,")",h,txids[holders.index(h)]
  526. def show_my_holding_addresses():
  527. my_holding_addresses = config.get('HoldingAddresses', 'addresses').split("+")
  528. for a in my_holding_addresses:
  529. print a
  530. def show_colors():
  531. sections = config.sections()
  532. for s in sections:
  533. if s in reserved_sections: continue
  534. print s,config.get(s, 'root_tx')
  535. def transfer_asset(sender, receivers,fee_size=None):
  536. address,txid,n = sender.split(":")
  537. tx_input = [(txid, int(n), address)]
  538. tx_outputs = []
  539. for l in receivers.split(","):
  540. address,amount = l.split(":")
  541. tx_outputs.append((address,int(float(amount)*1e8)))
  542. if fee_size:
  543. fee_p_out = sp.listunspent()[0]
  544. in_addr = base58_check_encode(binascii.unhexlify(fee_p_out['scriptPubKey'][6:-4]))
  545. change_address = config.get("bitcoind","change_address")
  546. change_amount = fee_p_out['amount']-fee_size
  547. tx_input.append((fee_p_out['txid'],fee_p_out['vout'],in_addr))
  548. tx_outputs.append((change_address, int(1e8*change_amount)))
  549. raw_transaction = maketx(tx_input, tx_outputs)
  550. def pay_to_shareholders(name, wallet_acct, total_payment_amount):
  551. holders = config.get(name, "holders").split("+")
  552. amounts = config.get(name, "amounts").split("+")
  553. total = 0.0
  554. for a in amounts:
  555. total += float(a)
  556. payouts = {}
  557. for h,a in zip(holders,amounts):
  558. d = total_payment_amount*float(a)/total
  559. payouts[h] = d
  560. sp.sendmany(wallet_acct,payouts)
  561. print "Payouts made:"
  562. for k in payouts.keys():
  563. print k,":",payouts[k]
  564. def transfer_others(transfer_other_from,transfer_other_to):
  565. naf = get_non_asset_funds(transfer_other_from)
  566. fee = int(1e8*0.005)
  567. total_value = 0
  568. inputs = []
  569. for u in naf:
  570. total_value += u['value']
  571. i = (u['tx_hash'], u['tx_output_n'], transfer_other_from)
  572. inputs.append(i)
  573. outputs = [(transfer_other_to, total_value-fee)]
  574. maketx(inputs,outputs,send=False)
  575. print "Paid",float(total_value-fee)/1e8,"to",transfer_other_to
  576. if __name__ == '__main__':
  577. # Process command-line options
  578. parser = OptionParser()
  579. parser.add_option('-p', '--paint', help='Paint coins for tracking', dest='paint_txid', action='store')
  580. parser.add_option('-n', '--new-address', help='Create new holding address for colored coins', dest='gen_address', default=False, action='store_true')
  581. parser.add_option('-l', '--list-colors', help='List of names of painted coins being tracked', dest='list_colors', default=False, action='store_true')
  582. parser.add_option('-u', '--update-ownership', help='Update ownership info for painted coins', dest='update_name', action='store')
  583. parser.add_option('-o', '--owners', help='Show owners of painted coins', dest="holders_name", action="store")
  584. parser.add_option('-m', '--my-holdings', help='Show holdings at my addresses', dest="show_holdings", action="store_true")
  585. parser.add_option('-a', '--holding-addresses', help='Show my holding addresses', dest="show_addresses", action="store_true")
  586. parser.add_option('-f', '--transfer-from', help='Asset to transfer to another address. address:txid:n', dest='transfer_from', action="store")
  587. parser.add_option('-t', '--transfer-to', help='Address to transfer asset to. address:amount,...', dest='transfer_to', action="store")
  588. parser.add_option('-d', '--pay-holders', help="Pay from your bitcoind wallet to asset holders: <asset_name>:<wallet_acctname>:<payout_amount>", dest="pay_to_holders", action="store")
  589. parser.add_option('-w', '--fee', help="Pay a transaction fee from your wallet when transferring an asset: <amount>", dest="fee", action="store")
  590. parser.add_option('-x', '--transfer-other-from', help='Transfer bitcoins UNRELATED to the tracked address/coins away from this address', dest="transfer_other_from", action="store")
  591. parser.add_option('-y', '--transfer-other-to', help='Transfer bitcoins UNRELATED to the tracked address/coins to this address', dest="transfer_other_to", action="store")
  592. opts, args = parser.parse_args()
  593. if opts.gen_address:
  594. print generate_holding_address()
  595. if opts.paint_txid:
  596. name,txid,n = opts.paint_txid.split(":")
  597. start_tracking_coins(name,txid+":"+n)
  598. if opts.holders_name:
  599. show_holders(opts.holders_name)
  600. if opts.update_name:
  601. update_tracked_coins(opts.update_name)
  602. if opts.list_colors:
  603. show_colors()
  604. if opts.show_holdings:
  605. show_my_holdings()
  606. if opts.show_addresses:
  607. show_my_holding_addresses()
  608. if opts.pay_to_holders:
  609. asset_name, wallet_acct_name, amount = opts.pay_to_holders.split(":")
  610. pay_to_shareholders(asset_name, wallet_acct_name, float(amount))
  611. if opts.transfer_from or opts.transfer_to:
  612. if opts.transfer_to and opts.transfer_from:
  613. if opts.fee:
  614. transfer_asset(opts.transfer_from, opts.transfer_to,fee_size=float(opts.fee))
  615. else:
  616. transfer_asset(opts.transfer_from, opts.transfer_to)
  617. else:
  618. print "Make sure you give both a source and destination"
  619. if opts.transfer_other_from or opts.transfer_other_to:
  620. if opts.transfer_other_to and opts.transfer_other_from:
  621. transfer_others(opts.transfer_other_from,opts.transfer_other_to)
  622. else:
  623. print "Make sure you give both a source and destination"

comments powered by Disqus