コード例 #1
0
ファイル: test_proxy.py プロジェクト: wdas/python-jsonrpc
    def test_http_ports(self, mock_httplib):
        setup_mock_httplib(mock_httplib)

        # http:// URL
        _ = jsonrpc.ServiceProxy('http://localhost/')
        http = MockHTTPConnection.current
        assert http.port == 80
        assert http.hostname == 'localhost'
        assert not http.is_https

        # http:// URL with custom port
        MockHTTPConnection.current = None
        _ = jsonrpc.ServiceProxy('http://example.com:1234/')
        http = MockHTTPConnection.current
        assert http.port == 1234
        assert http.hostname == 'example.com'
        assert not http.is_https

        # https:// URL
        MockHTTPConnection.current = None
        _ = jsonrpc.ServiceProxy('https://localhost/')
        http = MockHTTPConnection.current
        assert http.port == 443
        assert http.hostname == 'localhost'
        assert http.is_https

        # https:// URL with custom port
        MockHTTPConnection.current = None
        MockHTTPConnection.current = None
        _ = jsonrpc.ServiceProxy('https://example.com:4430/')
        http = MockHTTPConnection.current
        assert http.port == 4430
        assert http.hostname == 'example.com'
        assert http.is_https
コード例 #2
0
ファイル: merklemaker.py プロジェクト: 64octets/eloipool
    def _prepare(self):
        self.access = jsonrpc.ServiceProxy(self.UpstreamURI)

        self.currentBlock = (None, None, None)

        self.currentMerkleTree = None
        self.merkleRoots = deque(maxlen=self.WorkQueueSizeRegular[1])
        self.LowestMerkleRoots = self.WorkQueueSizeRegular[1]

        if not hasattr(self, 'WorkQueueSizeClear'):
            self.WorkQueueSizeClear = self.WorkQueueSizeLongpoll
        self._MaxClearSize = max(self.WorkQueueSizeClear[1],
                                 self.WorkQueueSizeLongpoll[1])
        self.clearMerkleTree = MerkleTree([self.clearCoinbaseTxn])
        self.clearMerkleRoots = Queue(self._MaxClearSize)
        self.LowestClearMerkleRoots = self.WorkQueueSizeClear[1]
        self.nextMerkleRoots = Queue(self._MaxClearSize)

        if not hasattr(self, 'WarningDelay'):
            self.WarningDelay = max(15, self.MinimumTxnUpdateWait * 2)
        if not hasattr(self, 'WarningDelayTxnLongpoll'):
            self.WarningDelayTxnLongpoll = self.WarningDelay
        if not hasattr(self, 'WarningDelayMerkleUpdate'):
            self.WarningDelayMerkleUpdate = self.WarningDelay

        self.lastMerkleUpdate = 0
        self.nextMerkleUpdate = 0
        global now
        now = time()
        self.updateMerkleTree()
コード例 #3
0
    def _prepare(self):
        self.access = jsonrpc.ServiceProxy(self.UpstreamURI)

        self.ready = False
        self.readyCV = threading.Condition()

        self.currentBlock = (None, None, None)
        self.lastBlock = (None, None, None)
        self.SubsidyAlgo = lambda height: 5000000000 >> (height // 210000)

        self.currentMerkleTree = None
        self.merkleRoots = deque(maxlen=self.WorkQueueSizeRegular[1])
        self.LowestMerkleRoots = self.WorkQueueSizeRegular[1]

        if not hasattr(self, 'WorkQueueSizeClear'):
            self.WorkQueueSizeClear = self.WorkQueueSizeLongpoll
        self._MaxClearSize = max(self.WorkQueueSizeClear[1],
                                 self.WorkQueueSizeLongpoll[1])
        self.clearMerkleRoots = Queue(self._MaxClearSize)
        self.LowestClearMerkleRoots = self.WorkQueueSizeClear[1]
        self.nextMerkleRoots = Queue(self._MaxClearSize)

        if not hasattr(self, 'WarningDelay'):
            self.WarningDelay = max(15, self.MinimumTxnUpdateWait * 2)
        if not hasattr(self, 'WarningDelayTxnLongpoll'):
            self.WarningDelayTxnLongpoll = self.WarningDelay
        if not hasattr(self, 'WarningDelayMerkleUpdate'):
            self.WarningDelayMerkleUpdate = self.WarningDelay

        self.lastMerkleUpdate = 0
        self.nextMerkleUpdate = 0
コード例 #4
0
ファイル: merklemaker.py プロジェクト: rsksmart/eloipool
	def _CallGBT(self, TS):
		access = jsonrpc.ServiceProxy(TS['uri'])
		self.logger.debug('Requesting new template from \'%s\'' % (TS['name'],))
		try:
			# First, try BIP 22 standard getblocktemplate :)
			MP = access.getblocktemplate(self.GBTReq)
			access.OldGMP = False
		except:
			try:
				# Failing that, give BIP 22 draft (2012-02 through 2012-07) getmemorypool a chance
				MP = access.getmemorypool(self.GMPReq)
			except:
				try:
					# Finally, fall back to bitcoind 0.5/0.6 getmemorypool
					MP = access.getmemorypool()
				except:
					MP = False
			if MP is False:
				# This way, we get the error from the BIP22 call if the old one fails too
				raise

			# Pre-BIP22 server (bitcoind <0.7 or Eloipool <20120513)
			if not access.OldGMP:
				access.OldGMP = True
				self.logger.warning('Upstream \'%s\' is not BIP 22 compatible' % (TS['name'],))
		
		return MP
コード例 #5
0
 def __init__(self, config, address, logger=None):
     """
     Check that the RPC library can be imported and set up the RPC http server connection
     """
     self.logger = logger if logger else logging.getLogger('null')
     self.address = address
     self.rpc = None
     try:
         import jsonrpc
     except ImportError:
         self.logger.warning('NuRPC: jsonrpc library could not be imported')
     else:
         # rpc connection
         self.JSONRPCException = jsonrpc.JSONRPCException
         opts = dict(tuple(line.strip().replace(' ', '').split('='))
                     for line in open(config).readlines() if len(line.split('=')) == 2)
         if 'rpcuser' not in opts.keys() or 'rpcpassword' not in opts.keys():
             self.logger.error("NuRPC: RPC parameters could not be read")
         else:
             try:
                 self.rpc = jsonrpc.ServiceProxy("http://%s:%[email protected]:%s" %
                                                 (opts['rpcuser'], opts['rpcpassword'], 14002))
                 self.txfee = self.rpc.getinfo()['paytxfee']
             except:
                 self.logger.error("NuRPC: RPC connection could not be established")
                 self.rpc = None
コード例 #6
0
ファイル: gmp-proxy.py プロジェクト: passoir/eloipool
def HandleLP():
    global server

    # FIXME: get path from gmp!
    pool = jsonrpc.ServiceProxy(sys.argv[1].rstrip('/') + '/LP')
    while True:
        try:
            mp = pool.getmemorypool()
            break
        except socket.timeout:
            pass
    jsonrpc_getwork._CheckForDupesHACK = {}
    makeMRD(mp)
    server.wakeLongpoll()
コード例 #7
0
ファイル: test_proxy.py プロジェクト: FireHost/python-jsonrpc
    def test_method_call_with_kwargs(self):
        s = jsonrpc.ServiceProxy("http://localhost/")

        http = MockHTTPConnection.current
        http.respdata = '{"result": {"foobar": true},"error":null,"id": 1}'

        echo = s.echo_kwargs(foobar=True)
        self.assertEquals(MockHTTPConnection.current.postdata,
                          jsonrpc.dumps({
                              'id': 1,
                              'jsonrpc': '2.0',
                              'method':'echo_kwargs',
                              'params': {'foobar': True},
                           }))
        self.assertEquals(echo, {'foobar': True})
コード例 #8
0
ファイル: test_proxy.py プロジェクト: wdas/python-jsonrpc
    def test_method_call_with_kwargs(self, mock_httplib):
        setup_mock_httplib(mock_httplib)
        s = jsonrpc.ServiceProxy("http://localhost/")

        http = MockHTTPConnection.current
        http.respdata = b'{"result": {"foobar": true},"error": null, "id": 1}'

        echo = s.echo_kwargs(foobar=True)
        expect = jsonrpc.dumps({
            'id': 1,
            'jsonrpc': '2.0',
            'method': 'echo_kwargs',
            'params': {
                'foobar': True
            },
        })
        assert expect == MockHTTPConnection.current.postdata
        assert echo == {'foobar': True}
コード例 #9
0
    def test_MethodCallCallsService(self):

        s = jsonrpc.ServiceProxy("http://localhost/")

        self.respdata = '{"result":"foobar","error":null,"id":""}'
        echo = s.echo("foobar")
        self.assertEquals(
            self.postdata,
            jsonrpc.dumps({
                "method": "echo",
                'params': ['foobar'],
                'id': 'jsonrpc'
            }))
        self.assertEquals(echo, 'foobar')

        self.respdata = '{"result":null,"error":"MethodNotFound","id":""}'
        try:
            s.echo("foobar")
        except jsonrpc.JSONRPCException, e:
            self.assertEquals(e.error, "MethodNotFound")
コード例 #10
0
ファイル: test_proxy.py プロジェクト: FireHost/python-jsonrpc
    def test_method_call(self):
        s = jsonrpc.ServiceProxy("http://localhost/")

        http = MockHTTPConnection.current
        http.respdata = '{"result":"foobar","error":null,"id": 1}'

        echo = s.echo('foobar')
        self.assertEquals(MockHTTPConnection.current.postdata,
                          jsonrpc.dumps({
                              'id': 1,
                              'jsonrpc': '2.0',
                              'method':'echo',
                              'params': ['foobar'],
                           }))
        self.assertEquals(echo, 'foobar')

        http.respdata='{"result":null,"error":"MethodNotFound","id":""}'
        try:
            s.echo('foobar')
        except jsonrpc.JSONRPCException,e:
            self.assertEquals(e.error, 'MethodNotFound')
コード例 #11
0
ファイル: rootstock.py プロジェクト: rsksmart/eloipool
def rootstockSubmissionThread(blkHash, blkHeader, coinbase, merkleHashes,
                              txnCount, share):
    servers = list(
        a for b in rootstockSubmissionThread.rootstock.RootstockSources
        for a in b)

    tries = 0
    start_time = None
    finish_time = None
    while len(servers):
        tries += 1
        RS = servers.pop(0)
        # Don't reuse the same connection object that getWork since we want the solution to be submitted asap
        #UpstreamRskdJSONRPC = RS['access']
        UpstreamRskdJSONRPC = jsonrpc.ServiceProxy(RS['uri'], timeout=3)
        try:
            start_time = datetime.now()
            # All parameters submitted to mnr_submitBitcoinBlockPartialMerkle must be hex formated
            UpstreamRskdJSONRPC.mnr_submitBitcoinBlockPartialMerkle(
                blkHash, blkHeader, coinbase, merkleHashes, txnCount)
            finish_time = datetime.now()
            rootstock.updateRootstock(True)
        except BaseException as gbterr:
            gbterr_fmt = traceback.format_exc()
            if tries > len(servers):
                msg = 'Upstream \'{0}\' block submission failed: {1}'.format(
                    RS['name'], gbterr_fmt)
                rootstockSubmissionThread.logger.error(msg)
                return
            servers.append(RS)
            continue
    if finish_time is not None:
        rootstockSubmissionThread.logger.info(
            "ROOTSTOCK: submitBitcoinBlock: {}, {}, {}, {}".format(
                start_time, finish_time, share['jobid'],
                b2a_hex(share['nonce']).decode('ascii')))
    else:
        rootstockSubmissionThread.logger.info(
            "submitBitcoinBlock failed: {}".format(tries))
コード例 #12
0
ファイル: test_proxy.py プロジェクト: wdas/python-jsonrpc
    def test_method_call(self, mock_httplib):
        setup_mock_httplib(mock_httplib)
        s = jsonrpc.ServiceProxy("http://localhost/")

        http = MockHTTPConnection.current
        http.respdata = b'{"result":"foobar","error":null,"id": 1}'

        echo = s.echo('foobar')
        expect = jsonrpc.dumps({
            'id': 1,
            'jsonrpc': '2.0',
            'method': 'echo',
            'params': ['foobar']
        })
        assert expect == MockHTTPConnection.current.postdata
        assert echo == 'foobar'

        http.respdata = b'{"result":null,"error":"MethodNotFound","id":""}'
        try:
            s.echo('foobar')
        except jsonrpc.JSONRPCException as e:
            assert e.error == 'MethodNotFound'
コード例 #13
0
ファイル: utils.py プロジェクト: wygiwyg/django-bitcoin
 def __init__(self, connection_string, main_account_name):
     self.bitcoind_api = jsonrpc.ServiceProxy(connection_string)
     self.account_name = main_account_name
コード例 #14
0
#'space' is how often the simulation outputs a datapoint
space = 100

#I don't remember why I did it this way, just leave 'c' alone unless you know what's up
c = starblk

#Configure RPC
#NUCONFIG='%s/.nu/nu.conf'%os.getenv("HOME")
#If you are windows, comment you the previous line and uncomment the following:
NUCONFIG = r'%s\nu\nu.conf' % os.getenv("APPDATA")
opts = dict(
    tuple(line.strip().replace(' ', '').split('='))
    for line in open(NUCONFIG).readlines())
try:
    rpc = jsonrpc.ServiceProxy(
        "http://%s:%[email protected]:%s" %
        (opts['rpcuser'], opts['rpcpassword'], opts.pop('rpcport', 14002)))
except:
    print "could not connect to nbt daemon"
    sys.exit(1)
try:
    nsrrpc = jsonrpc.ServiceProxy(
        "http://%s:%[email protected]:%s" %
        (opts['rpcuser'], opts['rpcpassword'], opts.pop('rpcport', 14001)))
except:
    print "could not connect to nsr daemon"
    sys.exit(1)
try:
    blkcnt = rpc.getblockcount()
except:
    print "Issues with RPC"
コード例 #15
0
if len(sys.argv) < 5:
    print(\
"""\
Usage: %s <file> <dest addr> <dest amount> {<fee-per-kb>}
Set BTCRPCURL=http://user:pass@localhost:portnum""" % sys.argv[0], file=sys.stderr)
    sys.exit()

COIN = 100000000


def unhexstr(str):
    return unhexlify(str.encode('utf8'))


proxy = jsonrpc.ServiceProxy(os.environ['BTCRPCURL'])


def select_txins(value):
    unspent = list(proxy.listunspent())
    random.shuffle(unspent)

    r = []
    total = 0
    for tx in unspent:
        total += tx['amount']
        r.append(tx)

        if total >= value:
            break
コード例 #16
0
#
#    Unless required by applicable law or agreed to in writing, software
#     distributed under the License is distributed on an "AS IS" BASIS,
#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#     See the License for the specific language governing permissions and
#     limitations under the License.

import subprocess
import os
import json
from decimal import Decimal
import math
import config
import jsonrpc

rpc_server = jsonrpc.ServiceProxy("http://" + config.RPC_USERNAME + ":" +\
        config.RPC_PASSWORD + "@127.0.0.1:" + str(config.RPC_PORT))

try:
    for account in config.ACCOUNTS:
        if account['coin'] == 'NBT':
            s = rpc_server.addmultisigaddress(account['sign_threshold'],
                                              account['pubkeys'],
                                              account['name'])
            print "Added multisig address to client, label =", account['name']
            if s == account['address']:
                print "Multisig address seems valid."
            else:
                print "Address does not match given public keys (note that order matters)"
except:
    print "Error verifying multisig address!"
コード例 #17
0
    rootlogger.addHandler(filehandler)


def RaiseRedFlags(reason):
	logging.getLogger('redflag').critical(reason)
	return reason


from bitcoin.node import BitcoinLink, BitcoinNode

bcnode = BitcoinNode(config.UpstreamNetworkId)
bcnode.userAgent += b'Eloipool:0.1/'

import jsonrpc

UpstreamBitcoindJSONRPC = jsonrpc.ServiceProxy(config.UpstreamURI)


try:
	import jsonrpc.authproxy
	jsonrpc.authproxy.USER_AGENT = 'Eloipool/0.1'
except:
	pass

from bitcoin.script import BitcoinScript
from bitcoin.txn import Txn
from base58 import b58decode
from struct import pack
import subprocess
from time import time
コード例 #18
0
#!/usr/bin/python
# Copyright (C) 2016 by Daniel Kraft <*****@*****.**>

# Find information about nearby loot and banks for a player.

import jsonrpc
import sys

name = "domob"
rpc = jsonrpc.ServiceProxy("http://*****:*****@localhost:8399/")


def distLInf(a, b):
    """
  Utility method to compute the L-infinity distance between
  the given two coordinates.
  """

    return max(abs(a[0] - b[0]), abs(a[1] - b[1]))


def pathlen(a, path):
    """
  Compute the L-infinity path length from a via the given
  list of way points.
  """

    if len(path) == 0:
        return 0
    res = distLInf(a, [path[0], path[1]])
    for i in range(2, len(path), 2):
コード例 #19
0

from binascii import b2a_hex
from copy import deepcopy
from math import ceil, log
from merklemaker import MakeBlockHeader
from struct import pack, unpack
import threading
from time import time
from util import PendingUpstream, RejectedShare, bdiff1target, blakehash, LEhash2int, swap32, target2bdiff, target2pdiff
import jsonrpc
import traceback

gotwork = None
if hasattr(config, 'GotWorkURI'):
	gotwork = jsonrpc.ServiceProxy(config.GotWorkURI)

if not hasattr(config, 'DelayLogForUpstream'):
	config.DelayLogForUpstream = False

if not hasattr(config, 'DynamicTargetting'):
	config.DynamicTargetting = 0
else:
	if not hasattr(config, 'DynamicTargetWindow'):
		config.DynamicTargetWindow = 120
	config.DynamicTargetGoal *= config.DynamicTargetWindow / 60

def submitGotwork(info):
	try:
		gotwork.gotwork(info)
	except:
コード例 #20
0
ファイル: rootstock.py プロジェクト: rsksmart/eloipool
 def _callGetWorkFrom(self, RS):
     access = jsonrpc.ServiceProxy(RS['uri'], timeout=3)
     return access.mnr_getWork()
コード例 #21
0
ファイル: bitcoin_addresses.py プロジェクト: nondejus/vibanko
import jsonrpc
import psycopg2
import time
import socket

rpc_username = "******"
rpc_password = "******"

db = psycopg2.connect(database="bitwallet",
                      user="******",
                      password="******")

bitcoin = jsonrpc.ServiceProxy("http://" + rpc_username + ":" + rpc_password +
                               "@127.0.0.1:8332/")

while True:
    try:
        c = db.cursor()
        c.execute("""
        SELECT COUNT(bitcoin_address)
        FROM bitcoin_addresses
        WHERE user_id IS NULL
        """)

        result = c.fetchone()

        if result:
            count = result[0]

            if count < 1000:
                for x in xrange(1000 - count):
コード例 #22
0
 def URI2Access(uri):
     if uri not in _URI2Access:
         access = jsonrpc.ServiceProxy(uri)
         access.OldGMP = False
         _URI2Access[uri] = access
     return _URI2Access[uri]
コード例 #23
0
ファイル: bitpaint.py プロジェクト: lonicera/aur
# Parse the config file
reserved_sections = ['bitcoind', 'HoldingAddresses']
config = ConfigParser.ConfigParser()
config.read(config_file)
rpchost = config.get('bitcoind', 'rpchost')
rpcport = config.get('bitcoind', 'rpcport')
rpcuser = config.get('bitcoind', 'rpcuser')
rpcpwd = config.get('bitcoind', 'rpcpwd')

# Connect to bitcoind
if len(rpcuser) == 0 and len(rpcpwd) == 0:
    bitcoind_connection_string = "http://*****:*****@%s:%s" % (rpcuser, rpcpwd,
                                                         rpchost, rpcport)
sp = jsonrpc.ServiceProxy(bitcoind_connection_string)

### End: Create/Read Config

### Start: Address Generation code
# The following code was yoinked from addrgen.py
# Thanks to: Joric/bitcoin-dev, june 2012, public domain
ssl = ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl') or 'libeay32')


def check_result(val, func, args):
    if val == 0: raise ValueError
    else: return ctypes.c_void_p(val)


ssl.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p
コード例 #24
0
ファイル: test_proxy.py プロジェクト: FireHost/python-jsonrpc
 def test_provides_proxy_method(self):
     s = jsonrpc.ServiceProxy("http://localhost/")
     self.assert_(callable(s.echo))
コード例 #25
0
ファイル: test_proxy.py プロジェクト: wdas/python-jsonrpc
 def test_provides_proxy_method(self, mock_httplib):
     setup_mock_httplib(mock_httplib)
     s = jsonrpc.ServiceProxy("http://localhost/")
     assert callable(s.echo)
コード例 #26
0
def blockSubmissionThread(payload, blkhash, share):
	if config.BlockSubmissions is None:
		servers = list(a for b in MM.TemplateSources for a in b)
	else:
		servers = list(config.BlockSubmissions)
	
	if hasattr(share['merkletree'], 'source_uri'):
		servers.insert(0, {
			'access': jsonrpc.ServiceProxy(share['merkletree'].source_uri),
			'name': share['merkletree'].source,
		})
	elif not servers:
		servers = list(a for b in MM.TemplateSources for a in b)
	
	myblock = (blkhash, payload[4:36])
	payload = b2a_hex(payload).decode('ascii')
	nexterr = 0
	tries = 0
	success = False
	while len(servers):
		tries += 1
		TS = servers.pop(0)
		UpstreamBitcoindJSONRPC = TS['access']
		try:
			# BIP 22 standard submitblock
			reason = UpstreamBitcoindJSONRPC.submitblock(payload)
		except BaseException as gbterr:
			gbterr_fmt = traceback.format_exc()
			try:
				try:
					# bitcoind 0.5/0.6 getmemorypool
					reason = UpstreamBitcoindJSONRPC.getmemorypool(payload)
				except:
					# Old BIP 22 draft getmemorypool
					reason = UpstreamBitcoindJSONRPC.getmemorypool(payload, {})
				if reason is True:
					reason = None
				elif reason is False:
					reason = 'rejected'
			except BaseException as gmperr:
				now = time()
				if now > nexterr:
					# FIXME: This will show "Method not found" on pre-BIP22 servers
					RaiseRedFlags(gbterr_fmt)
					nexterr = now + 5
				if MM.currentBlock[0] not in myblock and tries > len(servers):
					RBFs.append( (('next block', MM.currentBlock, now, (gbterr, gmperr)), payload, blkhash, share) )
					RaiseRedFlags('Giving up on submitting block to upstream \'%s\'' % (TS['name'],))
					if share['upstreamRejectReason'] is PendingUpstream:
						share['upstreamRejectReason'] = 'GAVE UP'
						share['upstreamResult'] = False
						logShare(share)
					return
				
				servers.append(TS)
				continue
		
		# At this point, we have a reason back
		if reason:
			# FIXME: The returned value could be a list of multiple responses
			msg = 'Upstream \'%s\' block submission failed: %s' % (TS['name'], reason,)
			if success and reason in ('stale-prevblk', 'bad-prevblk', 'orphan', 'duplicate'):
				# no big deal
				blockSubmissionThread.logger.debug(msg)
			else:
				RBFs.append( (('upstream reject', reason, time()), payload, blkhash, share) )
				RaiseRedFlags(msg)
		else:
			blockSubmissionThread.logger.debug('Upstream \'%s\' accepted block' % (TS['name'],))
			success = True
		if share['upstreamRejectReason'] is PendingUpstream:
			share['upstreamRejectReason'] = reason
			share['upstreamResult'] = not reason
			logShare(share)
コード例 #27
0
ファイル: gmp-proxy.py プロジェクト: passoir/eloipool
import jsonrpc_getwork
import merkletree
import socket
from struct import pack
import sys
import threading
from time import time
from util import RejectedShare

try:
    import jsonrpc.authproxy
    jsonrpc.authproxy.USER_AGENT = 'gmp-proxy/0.1'
except:
    pass

pool = jsonrpc.ServiceProxy(sys.argv[1])

worklog = {}
currentwork = [None, 0, 0]


def makeMRD(mp):
    coinbase = bytes.fromhex(mp['coinbasetxn'])
    cbtxn = bitcoin.txn.Txn(coinbase)
    cbtxn.disassemble()
    cbtxn.originalCB = cbtxn.getCoinbase()
    txnlist = [
        cbtxn,
    ] + list(map(bitcoin.txn.Txn, map(bytes.fromhex, mp['transactions'])))
    merkleTree = merkletree.MerkleTree(txnlist)
    merkleRoot = None
コード例 #28
0
ファイル: balances.py プロジェクト: rid3thespiral/ProfitLib
import jsonrpc
import json
from ProfitLib import *

daemons=json.loads(open("daemon_config.json").read())
exchanges=json.loads(open("exchange_config.json").read())
pl=ProfitLib(daemons, exchanges)
pl.GetMarketIDs()

balances={}
btcbal=Decimal(0)
for i, coin in enumerate(daemons):
  if (daemons[coin]["active"]==1):
    url="http://"+daemons[coin]["username"]+":"+daemons[coin]["passwd"]+"@"+daemons[coin]["host"]+":"+str(daemons[coin]["port"])
    b=jsonrpc.ServiceProxy(url)
    try:
      bal=b.getbalance()
      if (bal>0):
        bid=pl.GetBestBid(coin.split("_")[0])
        if (coin!="BTC"):
          balances[coin.split("_")[0]]=[str(bal), str((bid[0]*Decimal(bal)).quantize(Decimal("1.00000000"))), bid[1]]
          btcbal+=bid[0]*Decimal(bal)
        else:
          balances[coin.split("_")[0]]=[str(bal), str(bal), ""]
          btcbal+=Decimal(bal)
    except IOError:
      print coin+" offline"

exchtotals={}
for i, coin in enumerate(balances):
コード例 #29
0
ファイル: ProfitLib.py プロジェクト: rid3thespiral/ProfitLib
    def Calculate(self):
        self.GetMarketIDs()
        for i, coin in enumerate(self.daemons):
            if (self.daemons[coin]["active"] == 1
                ):  # only check active configs
                url = "http://" + self.daemons[coin][
                    "username"] + ":" + self.daemons[coin][
                        "passwd"] + "@" + self.daemons[coin][
                            "host"] + ":" + str(self.daemons[coin]["port"])
                hashrate = Decimal(
                    self.daemons[coin]["hashespersec"])  # our hashrate
                self.out[coin] = {}

                # connect to coind

                b = jsonrpc.ServiceProxy(url)

                # get block reward, including transaction fees
                # note #1: Novacoin (and coins derived from it?) report
                #          1% of actual value here
                # note #2: Namecoin doesn't support getblocktemplate, so get
                #          coinbase value from last block
                # note #3: PPCoin doesn't want any parameters passed to
                #          getblocktemplate.  Bitcoin requires at least
                #          an empty dictionary to be passed.  Others don't
                #          care.

                reward = Decimal(0)
                try:
                    reward = Decimal(b.getblocktemplate()["coinbasevalue"])
                except:
                    pass

                if (reward == 0):
                    try:
                        reward = Decimal(
                            b.getblocktemplate({})["coinbasevalue"])
                    except:
                        pass

                if (reward == 0):
                    try:
                        vouts = b.decoderawtransaction(
                            b.getrawtransaction(
                                b.getblock(b.getblockhash(
                                    b.getblockcount()))["tx"][0]))["vout"]
                        for j, vout in enumerate(vouts):
                            reward += vout["value"]
                    except:
                        pass

                if (coin == "NVC" or coin == "DEM" or coin == "OSC"
                        or coin == "PPC"):
                    reward *= 100

                # get proof-of-work difficulty
                # try getmininginfo first to minimize RPC calls; only use
                # getdifficulty if we must (as with NMC)

                algo = self.daemons[coin]["algo"]
                if (algo == "sha256"):
                    algo = "sha256d"
                try:
                    mining_info = b.getmininginfo()
                    diff = mining_info[
                        "difficulty_" +
                        algo]  # for MYR & other multi-algo coins
                    if (type(diff) is dict):
                        diff = diff["proof-of-work"]
                except:
                    try:
                        diff = mining_info["difficulty"]
                        if (type(diff) is dict):
                            diff = diff["proof-of-work"]
                    except:
                        diff = b.getdifficulty()
                        if (type(diff) is dict):
                            diff = diff["proof-of-work"]

                # get network hashrate
                # note 1: Novacoin reports this in MH/s, not H/s
                # note 2: Namecoin and Unobtanium don't report network hashrate, so
                #         return 0 (it's only informational anyway)

                try:
                    nethashrate = mining_info["networkhashps"]
                except:
                    try:
                        nethashrate = int(mining_info["netmhashps"] * 1000000)
                    except:
                        nethashrate = 0

                # ported from my C# implementation at
                # https://github.com/salfter/CoinProfitability/blob/master/CoinProfitabilityLibrary/Profitability.cs

                interval = Decimal(86400)  # 1 day
                target = Decimal(
                    ((65535 << 208) * 100000000000) / (diff * 100000000000))
                revenue = Decimal(interval * target * hashrate * reward /
                                  (1 << 256))

                # write to output dictionary

                self.out[coin]["reward"] = int(reward)
                self.out[coin]["difficulty"] = float(
                    Decimal(diff).quantize(Decimal("1.00000000")))
                self.out[coin]["nethashespersec"] = int(nethashrate)
                self.out[coin]["daily_revenue"] = int(revenue)

                # if not Bitcoin, get exchange rate and BTC equivalent

                if (coin != "BTC"):
                    bid = self.GetBestBid(coin.split(
                        "_")[0])  # 30 Jun 15: multi-algo compatibility
                    self.out[coin]["exchrate"] = float(
                        Decimal(bid[0]).quantize(Decimal("1.00000000")))
                    self.out[coin]["exchange"] = bid[1]
                    self.out[coin]["daily_revenue_btc"] = int(
                        Decimal(revenue * Decimal(bid[0])))
                else:
                    self.out[coin]["exchrate"] = float(
                        Decimal(100000000).quantize(Decimal("1.00000000")))
                    self.out[coin]["exchange"] = "n/a"
                    self.out[coin]["daily_revenue_btc"] = int(revenue)

                # copy these informational values from config dictionary

                self.out[coin]["algo"] = self.daemons[coin]["algo"]
                self.out[coin]["merged"] = self.daemons[coin]["merged"]

        return self.out