示例#1
0
def main():
    dir_data = load_setup(file("directory.conf").read())
    directory = [(kid, socket.gethostbyname(ip), port) for (kid, ip, port) in dir_data["directory"] ]
    special_id = dir_data["special"]
    
    parser = argparse.ArgumentParser(description='RSCoin auditor client.')
    
    parser.add_argument('--online_audit', action='store_true', help='randomly audit the mintettes behavior during current epoch')
    parser.add_argument('--local_test', action='store_true', help='test auditing function locally')
    parser.add_argument('--remote_test', action='store_true', help='')
    args = parser.parse_args()
    
    if args.online_audit:
        # Create two threads as follows
        threadNum = 30
        for _ in range(threadNum):
            auditor = Auditor(directory, special_id)
            
            try:
                thread.start_new_thread( auditor.start_online_audit,())
            except Exception, e:
                print "Error: unable to start thread %s" % e
            
            while 1:
                pass        
示例#2
0
def test_load_balance():
    try:
        dir_data = load_setup(file("directory.conf").read())
        directory = dir_data["directory"]
    except:
        chars = ["A", "B", "C", "D", "E", "F"]
        directory = [(c* 32, "127.0.0.1", 8080) for c in chars]

    hist = defaultdict(int)
    for _ in range(10000):
        x = get_authorities(directory, urandom(32), N = 3)
        for xi in x:
            hist[xi] += 1

    for ki, ni in sorted(hist.iteritems()):
        print hexlify(ki)[:8], ni
示例#3
0
def test_load_balance():
    try:
        dir_data = load_setup(file("directory.conf").read())
        directory = dir_data["directory"]
    except:
        chars = ["A", "B", "C", "D", "E", "F"]
        directory = [(c * 32, "127.0.0.1", 8080) for c in chars]

    hist = defaultdict(int)
    for _ in range(10000):
        x = get_authorities(directory, urandom(32), N=3)
        for xi in x:
            hist[xi] += 1

    for ki, ni in sorted(hist.iteritems()):
        print hexlify(ki)[:8], ni
示例#4
0
def test_setup():
    data = """{
        "special": "AmodBjXyo2bVqyi1h0e5Kf8hSbGCmalnbF8YwJ0=",
        "directory": [ ["A/Sw7CRkoXzB2O0A3WfPMSDIbv/pOxd5Co3u9kM=", "127.0.0.1", 8080] ] 
    }"""

    stuff = load_setup(data)
    
    secret = "hello1"
    special = "special"
    directory = stuff["directory"]

    public = rscoin.Key(secret, public=False).pub.export()
    print("\nPublic: %s" % b64encode(public)) # , b64decode

    public_special = rscoin.Key(special, public=False).pub.export()
    print("Public (special): %s" % b64encode(public_special)) # , b64decode

    assert public == directory[0][0]
    assert public_special == stuff["special"]
示例#5
0
def test_setup():
    data = """{
        "special": "AmodBjXyo2bVqyi1h0e5Kf8hSbGCmalnbF8YwJ0=",
        "directory": [ ["A/Sw7CRkoXzB2O0A3WfPMSDIbv/pOxd5Co3u9kM=", "127.0.0.1", 8080] ] 
    }"""

    stuff = load_setup(data)

    secret = "hello1"
    special = "special"
    directory = stuff["directory"]

    public = rscoin.Key(secret, public=False).pub.export()
    print("\nPublic: %s" % b64encode(public))  # , b64decode

    public_special = rscoin.Key(special, public=False).pub.export()
    print("Public (special): %s" % b64encode(public_special))  # , b64decode

    assert public == directory[0][0]
    assert public_special == stuff["special"]
示例#6
0
文件: rsc.py 项目: dazhxu/rscoin
def main():
    dir_data = load_setup(file("directory.conf").read())
    # directory = dir_data["directory"]

    directory = [(kid, socket.gethostbyname(ip), port)
                 for (kid, ip, port) in dir_data["directory"]]

    special_id = dir_data["special"]

    # Options
    parser = argparse.ArgumentParser(description='RSCoin client.')
    parser.add_argument('--dir', action='store_true', help='List mintettes.')
    parser.add_argument('--mock',
                        action='store_true',
                        help='Do not connect to the network.')
    parser.add_argument('--balances',
                        action='store_true',
                        help='List balances of all addresses.')

    parser.add_argument('--issue',
                        nargs=2,
                        metavar=("VALUE", "ADDRESS"),
                        help='Issue a coin to an address.')
    parser.add_argument('--pay',
                        nargs=3,
                        metavar=("VALUE", "ADDRESS", "CHANGEADDRESS"),
                        help='Pay and address some amount, and return change')

    parser.add_argument('--newaddress',
                        nargs=1,
                        metavar="NAME",
                        help='Make a new address with a specific name.')
    parser.add_argument('--storeaddress',
                        nargs=2,
                        metavar=("NAME", "KEYID"),
                        help='Load an address ID with a specific name.')
    parser.add_argument('--listaddress',
                        action='store_true',
                        help='List all known addresses.')

    parser.add_argument('--play',
                        nargs=1,
                        metavar="FILE",
                        help='Play a set of transaction cores.')

    parser.add_argument('--conn',
                        default=20,
                        type=int,
                        metavar="CONNECTIONS",
                        help='Number of simultaneaous connections.')

    args = parser.parse_args()

    if args.dir:
        for (kid, ip, port) in directory:
            print "%s\t%s\t%s" % (ip, port, b64encode(kid))

    elif args.balances:
        keys = load_keys()
        active = ActiveTx("activetx.log", keys)
        for (k, v) in active.balances().iteritems():
            print "%s\t%s RSC" % (k, v)

    elif args.listaddress:
        keys = load_keys()

        for k in keys:
            if k[0] == "#":
                print "%s\t%s (%s)" % (k, keys[k][2], keys[k][1])

    elif args.newaddress:
        sec_str = urandom(32)
        k_sec = rscoin.Key(sec_str, public=False)
        k_pub = k_sec.pub.export()
        k_id = k_sec.id()

        f = file("keychain.txt", "a")
        data = "#%s sec %s %s" % (args.newaddress[0], b64encode(k_id),
                                  b64encode(sec_str))
        print data
        f.write(data + "\n")
        f.close()

    elif args.storeaddress:
        f = file("keychain.txt", "a")
        data = "#%s pub %s" % (args.storeaddress[0], args.storeaddress[1])
        f.write(data + "\n")
        f.close()

    elif args.play:

        threads = [None] * args.conn
        cores = []

        for core in file(args.play[0]):
            c = core.strip().split()
            cores += [c]

        def play_another_song(var):
            if var is not None and (not isinstance(var, float)
                                    or not isinstance(var, float)):
                print "ERROR", var

            if cores != []:
                c = cores.pop()
                d = play(c, directory)
                d.addCallback(play_another_song)

                def replay():
                    cores += [c]

                d.addErrback(replay)
                d.addErrback(play_another_song)

            else:
                threads.pop()
                if threads == []:
                    reactor.stop()

        for _ in threads:
            play_another_song(None)

        t0 = default_timer()
        reactor.run()
        t1 = default_timer()

        print "Overall time: %s" % (t1 - t0)
        for (ip, v) in sorted(_stats.iteritems()):
            print "Stats: %s %s" % (ip, v)

    elif args.pay:

        (val, dest_addr, change_addr) = args.pay
        val = int(val)
        assert isinstance(val, int) and 0 < val

        keys = load_keys()
        dest_addr = b64decode(keys["#" + dest_addr][2])
        change_addr = b64decode(keys["#" + change_addr][2])

        active = ActiveTx("activetx.log", keys)

        print val
        xval, txs = active.get_value(int(val))
        assert len(txs) > 0

        if val <= xval:
            # build the transactions
            inTx = []
            outTx = [rscoin.OutputTx(dest_addr, val)]
            if xval - val > 0:
                outTx += [rscoin.OutputTx(change_addr, xval - val)]

            inTx_list = []
            keys_list = []
            for (tx_id, i, key_id, value) in txs:
                inTx_list += [
                    rscoin.Tx.parse(active.Tx[(tx_id, i, key_id, value)])
                ]
                keys_list += [rscoin.Key(b64decode(keys[key_id][3]), False)]
                inTx += [rscoin.InputTx(tx_id, i)]

            newtx = rscoin.Tx(inTx, outTx)
            newtx_ser = newtx.serialize()

            ## Now we sign and remove from the list
            active.add(newtx_ser)
            for k in txs:
                active.remove(k)

            active.save(reactor)

            ## Now run the on-line checking
            sechash, query_string, core = package_query(
                newtx, inTx_list, keys_list)
            print " ".join(core)

            d = play(core, directory)
            d.addBoth(r_stop)

            reactor.run()

        else:
            print "Insufficient balance: %s ( < %s)" % (val, xval)

    elif args.issue:

        # Parse the basic files.
        secret = file("secret.key").read()
        mykey = rscoin.Key(secret, public=False)

        # Ensure the secret key corresponds to the special public key.
        assert special_id == mykey.id()

        [value_str, key_name] = args.issue

        keys = load_keys()
        key_id = b64decode(keys["#" + key_name][2])

        tx = rscoin.Tx([], [rscoin.OutputTx(key_id, int(value_str))])
        sig = mykey.sign(tx.id())

        ## Now we test the Commit
        tx_ser = tx.serialize()
        #core = map(b64encode, [tx_ser, mykey.pub.export(), sig])
        #data = " ".join(["Commit", str(len(core))] + core)

        data = package_issue(tx, [mykey, sig])

        if args.mock:
            print data
        else:

            auths = set(get_authorities(directory, tx.id()))
            small_dir = [(kid, ip, port) for (kid, ip, port) in directory
                         if kid in auths]

            d = broadcast(small_dir, data)

            def r_process(results):
                for msg in results:
                    parsed = unpackage_commit_response(msg)
                    if parsed[0] != "OK":
                        raise Exception("Response not OK.")

                    pub, sig = parsed[1:]
                    kx = rscoin.Key(pub)

                    if not (kx.verify(tx.id(), sig) and kx.id() in auths):
                        raise Exception("Invalid Signature.")

                    auths.remove(kx.id())

                active = ActiveTx("activetx.log", keys)
                active.add(tx_ser)
                active.save(reactor)

                print " ".join(core)

            d.addCallback(r_process)
            d.addBoth(r_stop)
            reactor.run()
示例#7
0
from twisted.application import internet, service
from rscoin.rscservice import RSCFactory, load_setup

import rscoin
from base64 import b64encode, b64decode


secret = file("secret.key").read()
public = rscoin.Key(secret, public=False)
print "Public keys: %s" % b64encode(public.pub.export())

dir_data = file("directory.conf").read()
directory = load_setup(dir_data) # [(public.id(), "127.0.0.1", 8080)]

application = service.Application("rscoin")
echoService = internet.TCPServer(8080, RSCFactory(secret, directory["directory"], directory["special"], N=3))
echoService.setServiceParent(application)

示例#8
0
from twisted.application import internet, service
from rscoin.rscservice import RSCFactory, load_setup

import rscoin
from base64 import b64encode, b64decode

secret = file("secret.key").read()
public = rscoin.Key(secret, public=False)
print "Public keys: %s" % b64encode(public.pub.export())

dir_data = file("directory.conf").read()
directory = load_setup(dir_data)  # [(public.id(), "127.0.0.1", 8080)]

application = service.Application("rscoin")
echoService = internet.TCPServer(
    8080, RSCFactory(secret, directory["directory"], directory["special"],
                     N=3))
echoService.setServiceParent(application)
示例#9
0
def main():    
    dir_data = load_setup(file("directory.conf").read())
    # directory = dir_data["directory"]

    directory = [(kid, socket.gethostbyname(ip), port) for (kid, ip, port) in dir_data["directory"] ]

    special_id = dir_data["special"]

    # Options
    parser = argparse.ArgumentParser(description='RSCoin client.')
    parser.add_argument('--dir', action='store_true', help='List mintettes.')
    parser.add_argument('--mock', action='store_true', help='Do not connect to the network.')
    parser.add_argument('--balances', action='store_true', help='List balances of all addresses.')
    

    parser.add_argument('--issue', nargs=2, metavar=("VALUE", "ADDRESS"), help='Issue a coin to an address.')
    parser.add_argument('--pay', nargs=3, metavar=("VALUE", "ADDRESS", "CHANGEADDRESS"),  help='Pay and address some amount, and return change')

    parser.add_argument('--newaddress', nargs=1, metavar="NAME", help='Make a new address with a specific name.')
    parser.add_argument('--storeaddress', nargs=2, metavar=("NAME", "KEYID"), help='Load an address ID with a specific name.')
    parser.add_argument('--listaddress',action='store_true', help='List all known addresses.')

    parser.add_argument('--play', nargs=1, metavar="FILE", help='Play a set of transaction cores.')

    parser.add_argument('--conn', default=20, type=int, metavar="CONNECTIONS", help='Number of simultaneaous connections.')
    
    
    args = parser.parse_args()

    if args.dir:
        for (kid, ip, port) in directory:
            print "%s\t%s\t%s" % (ip, port, b64encode(kid))

    elif args.balances:
        keys = load_keys()
        active = ActiveTx("activetx.log", keys)
        for (k, v) in active.balances().iteritems():
            print "%s\t%s RSC" % (k, v)
        
    elif args.listaddress:
        keys = load_keys()
        
        for k in keys:
            if k[0] == "#":
                print "%s\t%s (%s)" % (k, keys[k][2], keys[k][1])

    elif args.newaddress:
        sec_str = urandom(32)
        k_sec = rscoin.Key(sec_str, public=False)
        k_pub = k_sec.pub.export()
        k_id = k_sec.id()
        
        f = file("keychain.txt", "a")
        data = "#%s sec %s %s" % (args.newaddress[0], b64encode(k_id), b64encode(sec_str))
        print data
        f.write(data+"\n")
        f.close()

    elif args.storeaddress:
        f = file("keychain.txt", "a")
        data = "#%s pub %s" % (args.storeaddress[0], args.storeaddress[1])
        f.write(data+"\n")
        f.close()

    elif args.play:

        threads = [ None ] * args.conn
        cores = []

        for core in file(args.play[0]):
            c = core.strip().split()
            cores += [ c ]

        def play_another_song(var):
            if var is not None and (not isinstance(var, float) or not isinstance(var, float)):
                print "ERROR", var                

            if cores != []:
                c = cores.pop()
                d = play(c, directory)
                d.addCallback(play_another_song)

                def replay(failure):
                    cores.append(c)
                    print cores + len(cores)

                d.addErrback(replay)
                d.addErrback(play_another_song)

            else:
                threads.pop()
                if threads == []:
                    reactor.stop()
        
        for _ in threads:
            play_another_song(None)

        t0 = default_timer()
        reactor.run()
        t1 = default_timer()
        
        print "Overall time: %s" % (t1 - t0)
        for (ip, v) in sorted(_stats.iteritems()):
            print "Stats: %s %s" % (ip, v)

    elif args.pay:

        (val, dest_addr, change_addr) = args.pay
        val = int(val)
        assert isinstance(val, int) and 0 < val 

        keys = load_keys()
        dest_addr = b64decode(keys["#"+dest_addr][2])
        change_addr = b64decode(keys["#"+change_addr][2])

        active = ActiveTx("activetx.log", keys)
        
        print val
        xval, txs = active.get_value(int(val))
        assert len(txs) > 0

        if val <= xval:
            # build the transactions
            inTx = []
            outTx = [ rscoin.OutputTx(dest_addr, val) ] 
            if xval - val > 0:
                outTx += [ rscoin.OutputTx(change_addr, xval - val) ]

            inTx_list = []
            keys_list = []
            for (tx_id, i, key_id, value) in txs:
                inTx_list += [ rscoin.Tx.parse(active.Tx[(tx_id, i, key_id, value)]) ]
                keys_list += [ rscoin.Key(b64decode(keys[key_id][3]), False) ]
                inTx += [ rscoin.InputTx(tx_id, i) ]
            
            newtx = rscoin.Tx(inTx, outTx)
            newtx_ser = newtx.serialize()
            
            ## Now we sign and remove from the list
            active.add(newtx_ser)
            for k in txs:
                active.remove(k)

            active.save(reactor)

            ## Now run the on-line checking
            sechash, query_string, core = package_query(newtx, inTx_list, keys_list)
            print " ".join(core)

            d = play(core, directory)
            d.addBoth(r_stop)
            
            reactor.run()

        else:
            print "Insufficient balance: %s ( < %s)" % (val, xval)


    elif args.issue:
    
        # Parse the basic files.
        secret = file("secret.key").read()
        mykey = rscoin.Key(secret, public=False)

        # Ensure the secret key corresponds to the special public key.
        assert special_id == mykey.id()

        [value_str, key_name] = args.issue
        
        keys = load_keys()
        key_id = b64decode(keys["#"+key_name][2])

        tx = rscoin.Tx([], [rscoin.OutputTx(key_id, int(value_str))])
        sig = mykey.sign(tx.id())

        ## Now we test the Commit
        #tx_ser = tx.serialize()
        #core = map(b64encode, [tx_ser, mykey.pub.export(), sig])
        #data = " ".join(["Commit", str(len(core))] + core)

        data = package_issue(tx, [mykey, sig])

        if args.mock:
            print data
        else:

            auths = set(get_authorities(directory, tx.id()))
            small_dir = [(kid, ip, port) for (kid, ip, port) in directory if kid in auths]

            d = broadcast(small_dir, data)

            def r_process(results):
                for msg in results:
                    parsed = unpackage_commit_response(msg) 
                    if parsed[0] != "OK":
                        raise Exception("Response not OK.")

                    pub, sig = parsed[1:]
                    kx = rscoin.Key(pub)
                        
                    if not (kx.verify(tx.id(), sig) and kx.id() in auths):
                        raise Exception("Invalid Signature.")

                    auths.remove( kx.id() )         

                active = ActiveTx("activetx.log", keys)
                active.add(tx_ser)
                active.save(reactor)

                print " ".join(core)

            d.addCallback(r_process)
            d.addBoth(r_stop)
            reactor.run()