Esempio n. 1
0
def test2(fname, expected):
    data = util.load_str_lines_list(fname)
    prog = []
    for line in data:
        op, arg = line.split()
        prog.append([op, int(arg)])

    done = False
    acc = 0
    ip = 0
    for instr, arg in prog:
        fixed_prog = prog.copy()
        if instr == 'nop':
            fixed_prog[ip] = ['jmp', arg]
        elif instr == 'jmp':
            fixed_prog[ip] = ['nop', arg]
        else:
            ip += 1
            continue

        ip += 1
        done, acc = run(fixed_prog)
        if done:
            break

    util.assert_equal(acc, expected)
Esempio n. 2
0
def test_cov():
    A = np.random.randn(20, 20)
    M1 = A.T @ A
    gp = lgp.GP()
    gp.addcov(M1, 'M')
    M2 = gp.prior('M', raw=True)
    util.assert_equal(M1, M2)
Esempio n. 3
0
def test2(data, expected):
    seats = map(decode, data)
    hi = max(seats)
    lo = min(seats)
    free_seats = set(range(lo, hi + 1)) - set(seats)
    my_seat = free_seats.pop()
    util.assert_equal(my_seat, expected)
Esempio n. 4
0
def test_tree():
    dtypes = [
        [('f0', float)],
        'f,f',
        'f,d,f',
        'f,O',
        'S25,U10,?',
        [('a', 'f,f', (3, 1)), ('b', [('c', 'd,d'), ('e', '?', 15)])],
    ]
    shapes = [
        (),
        (0,),
        (1,),
        (1, 0),
        (0, 1),
        (10,),
        (1, 2, 3),
        (2, 3, 4),
    ]
    for dtype, shape in itertools.product(dtypes, shapes):
        array1 = random_array(shape, dtype)
        array = lgp.StructuredArray(array1)
        children, aux_data = tree_util.tree_flatten(array)
        array = tree_util.tree_unflatten(aux_data, children)
        array2 = np.asarray(array)
        util.assert_equal(array1, array2)
Esempio n. 5
0
def test_no_checksym():
    covs = []
    for checksym in [False, True]:
        gp = lgp.GP(lgp.ExpQuad(), checksym=checksym)
        gp.addx({'x': np.arange(20)})
        covs.append(gp.prior('x', raw=True))
    util.assert_equal(*covs)
Esempio n. 6
0
  def checkNameStatus (self, data, name, value, expired, transferred):
    """
    Check a name_list entry for the expected data.
    """

    self.checkNameData (data, name, value, None, expired)
    assert_equal (data['transferred'], transferred)
Esempio n. 7
0
def test(data, expected):
    result = 0
    for d in data:
        s = set(d.keys())
        if len(REQUIRED_FIELDS - s) == 0:
            result += 1
    util.assert_equal(result, expected)
Esempio n. 8
0
def test_zero_covblock():
    gp = lgp.GP()
    a = np.random.randn(10, 10)
    m = a.T @ a
    gp.addcov(m, 0)
    gp.addcov(m, 1)
    prior = gp.prior(raw=True)
    util.assert_equal(prior[0, 1], np.zeros_like(m))
Esempio n. 9
0
def test1(fname, expected):
    data = util.load_str_lines_list(fname)
    rules = dict()
    for line in data:
        outer, inner = parse1(line)
        rules[outer] = inner

    result = len(allOuters(rules, 'shiny gold'))
    util.assert_equal(result, expected)
Esempio n. 10
0
def test_pred_all():
    gp = lgp.GP(lgp.ExpQuad())
    x, y, z = np.random.randn(3, 20)
    gp.addx(x, 0)
    gp.addx(y, 1)
    m1, c1 = gp.predfromdata({0: z}, raw=True)
    m2, c2 = gp.predfromdata({0: z}, [0, 1], raw=True)
    util.assert_equal(m1, m2)
    util.assert_equal(c1, c2)
Esempio n. 11
0
def test_addcov_missing_block():
    gp = lgp.GP(lgp.ExpQuad())
    gp.addcov({
        (0, 0): np.ones((2, 2)),
        (1, 1): np.ones((3, 3)),
        (0, 1): np.ones((2, 3)),
    })
    prior = gp.prior(raw=True)
    util.assert_equal(prior[0, 1], prior[1, 0].T)
Esempio n. 12
0
def test_priorpoints_cache():
    gp = lgp.GP(lgp.ExpQuad())
    x = np.arange(20)
    gp.addx(x, 0)
    gp.addx(x, 1)
    prior = gp.prior()
    cov = gvar.evalcov(prior)
    util.assert_equal(cov[0, 0], cov[1, 1])
    util.assert_equal(cov[0, 0], cov[0, 1])
Esempio n. 13
0
def test1(fname, expected):
    asm = Asm(fname)

    try:
        asm.run_no_loop()
    except Exception:
        pass

    util.assert_equal(asm.acc, expected)
Esempio n. 14
0
 def check_tree_decomp(self, conversion):
     for n in self.sizes:
         K = self.randsymmat(n)
         b = self.randmat(n)
         d1 = self.decompclass(K)
         q1 = d1.quad(b)
         d2 = conversion(d1)
         q2 = d2.quad(b)
         util.assert_equal(q1, q2)
Esempio n. 15
0
def test_addprocderiv():
    gp = lgp.GP(lgp.ExpQuad())
    gp.addprocderiv(1, 'a')
    x = np.arange(20)
    gp.addx(x, 0, proc='a')
    gp.addx(x, 1, deriv=1)
    prior = gp.prior(raw=True)
    util.assert_equal(prior[0, 0], prior[1, 1])
    util.assert_equal(prior[0, 0], prior[0, 1])
Esempio n. 16
0
def test_default_kernel():
    gp = lgp.GP(lgp.ExpQuad())
    gp.addproc(key='a')
    x = np.arange(20)
    gp.addx(x, 'x1')
    gp.addx(x, 'x2', proc='a')
    prior = gp.prior(raw=True)
    util.assert_equal(prior['x1', 'x1'], prior['x2', 'x2'])
    util.assert_equal(prior['x1', 'x2'], np.zeros(2 * x.shape))
Esempio n. 17
0
def test2(fname, expected):
    data = util.load_str_lines_list(fname)
    rules = dict()
    for line in data:
        outer, inner = parse2(line)
        rules[outer] = inner

    result = countInner(rules, 'shiny gold') - 1
    util.assert_equal(result, expected)
Esempio n. 18
0
def test1(data, expected):
    result = 0
    for d in data:
        s = set(d.keys())
        required = set(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])
        if len(required - s) == 0:
            result += 1
#        else:
#            print('invalid', d)
    util.assert_equal(result, expected)
Esempio n. 19
0
def test_empty_proc():
    gp = lgp.GP()
    gp.addproctransf({}, 'a')
    gp.addproclintransf(lambda: lambda x: 0, [], 'b')
    x = np.arange(20)
    gp.addx(x, 'ax', proc='a')
    gp.addx(x, 'bx', proc='b')
    cov = gp.prior(raw=True)
    util.assert_equal(cov['ax', 'ax'], np.zeros(2 * x.shape))
    util.assert_equal(cov['bx', 'bx'], np.zeros(2 * x.shape))
Esempio n. 20
0
def test_zero_givencov():
    gp = lgp.GP(lgp.ExpQuad())
    x, y, z = np.random.randn(3, 20)
    gp.addx(x, 0)
    gp.addx(y, 1)
    cov = np.zeros(2 * x.shape)
    m1, c1 = gp.predfromdata({0: z}, 1, {(0, 0): cov}, raw=True)
    m2, c2 = gp.predfromdata({0: z}, 1, raw=True)
    util.assert_equal(m1, m2)
    util.assert_equal(c1, c2)
Esempio n. 21
0
  def checkList (self, data, names):
    """
    Check that the result in 'data' contains the names
    given in the array 'names'.
    """

    def walker (e):
      return e['name']
    dataNames = map (walker, data)

    assert_equal (dataNames, names)
Esempio n. 22
0
 def test_pow(self):
     for kw in self.kwargs_list:
         kernel = self.kernel_class(**kw)
         with pytest.raises(TypeError):
             kernel = kernel**kernel
         k1 = kernel**2
         k2 = kernel * kernel
         x = self.random_x(**kw)[:, None]
         c1 = k1(x, x.T)
         c2 = k2(x, x.T)
         util.assert_equal(c1, c2)
Esempio n. 23
0
def test_solver_cache():
    gp = lgp.GP(lgp.ExpQuad())
    x = np.linspace(0, 1, 10)
    y = np.linspace(1, 2, 10)
    z = np.zeros_like(x)
    gp.addx(x, 0)
    gp.addx(y, 1)
    m1, c1 = gp.predfromdata({0: z}, 1, raw=True)
    m2, c2 = gp.predfromdata({0: z}, 1, raw=True)
    util.assert_equal(m1, m2)
    util.assert_equal(c1, c2)
Esempio n. 24
0
def test(fname: str, new_state, expected: int):
    data = util.load_str_lines_list(fname)
    seats = data
    while True:
    #    show(seats)
        seats2 = apply_rules(seats, new_state)
        if seats == seats2:
            break
        seats = seats2

    result = ''.join(seats).count('#')
    util.assert_equal(result, expected)
Esempio n. 25
0
 def test_rescale_swap(self):
     for kw in self.kwargs_list:
         kernel = self.kernel_class(**kw)
         x = self.random_x(**kw)[:, None]
         y = self.random_x(**kw)[None, :]
         x0 = x[0]
         f = lambda x: np.where(x < x0, -1, 1)
         k1 = kernel.rescale(f, None)
         k2 = kernel.rescale(None, f)
         c1 = k1(x, y)
         c2 = k2(y, x)
         util.assert_equal(c1, c2)
Esempio n. 26
0
 def test_xtransf_swap(self):
     for kw in self.kwargs_list:
         kernel = self.kernel_class(**kw)
         x = self.random_x(**kw)
         y = self.random_x(**kw)[None, :]
         xt = np.arange(len(x))
         f = lambda xt: x[xt]
         xt = xt[:, None]
         k1 = kernel.xtransf(f, None)
         k2 = kernel.xtransf(None, f)
         c1 = k1(xt, y)
         c2 = k2(y, xt)
         util.assert_equal(c1, c2)
Esempio n. 27
0
def test_partial_derivative():
    gp = lgp.GP(lgp.ExpQuad())
    x = np.arange(20)
    y = np.zeros(len(x), 'f8,f8')
    y['f0'] = x
    gp.addx(y, 0, deriv='f0')
    cov1 = gp.prior(0, raw=True)

    gp = lgp.GP(lgp.ExpQuad())
    gp.addx(x, 0, deriv=1)
    cov2 = gp.prior(0, raw=True)

    util.assert_equal(cov1, cov2)
Esempio n. 28
0
 def test_fourier_swap(self):
     for kw in self.kwargs_list:
         kernel = self.kernel_class(**kw)
         try:
             kernel.fourier(True, None)
         except NotImplementedError:
             pytest.skip()
         x = self.random_x(**kw)[:, None]
         k = np.arange(1, 11)[None, :]
         k1 = kernel.fourier(True, None)
         k2 = kernel.fourier(None, True)
         c1 = k1(k, x)
         c2 = k2(x, k)
         util.assert_equal(c1, c2)
Esempio n. 29
0
    def checkNameHistory(self, ind, name, values):
        """
    Query for the name_history of 'name' and check that its historical
    values, in order of increasing height, are the ones in 'values'.
    """

        data = self.nodes[ind].name_history(name)

        valuesFound = []
        for e in data:
            assert_equal(e['name'], name)
            valuesFound.append(e['value'])

        assert_equal(valuesFound, values)
Esempio n. 30
0
def test_addprocxtransf():
    gp = lgp.GP()
    f = lambda x: x**2
    gp.addproc(lgp.ExpQuad(), 0)
    gp.addprocxtransf(f, 'a', 0)
    gp.addproclintransf(lambda g: lambda x: g(f(x)), [0], 'b')
    x = np.linspace(0, 4, 20)
    gp.addx(x, 0, proc='a')
    gp.addx(x, 1, proc='b')
    gp.addx(f(x), 2, proc=0)
    prior = gp.prior(raw=True)
    for i in range(3):
        for j in range(3):
            util.assert_equal(prior[0, 0], prior[i, j])
Esempio n. 31
0
  def checkUTXO (self, ind, name, shouldBeThere):
    """
    Query for a name's coin in the UTXO set and check that it is either
    there or not.
    """

    data = self.nodes[ind].name_show (name)
    txo = self.nodes[ind].gettxout (data['txid'], data['vout'])

    if shouldBeThere:
      assert txo is not None
      assert_equal (txo['scriptPubKey']['nameOp']['name'], name)
    else:
      assert txo is None
Esempio n. 32
0
  def checkNameHistory (self, ind, name, values):
    """
    Query for the name_history of 'name' and check that its historical
    values, in order of increasing height, are the ones in 'values'.
    """

    data = self.nodes[ind].name_history (name)

    valuesFound = []
    for e in data:
      assert_equal (e['name'], name)
      valuesFound.append (e['value'])

    assert_equal (valuesFound, values)
Esempio n. 33
0
    def checkNameData(self, data, name, value, expiresIn, expired):
        """
    Check a name info object against expected data.
    """

        assert_equal(data['name'], name)
        assert_equal(data['value'], value)
        if (expiresIn is not None):
            assert_equal(data['expires_in'], expiresIn)
        assert_equal(data['expired'], expired)
Esempio n. 34
0
  def checkNameData (self, data, name, value, expiresIn, expired):
    """
    Check a name info object against expected data.
    """

    assert_equal (data['name'], name)
    assert_equal (data['value'], value)
    if (expiresIn is not None):
      assert_equal (data['expires_in'], expiresIn)
    assert_equal (data['expired'], expired)
Esempio n. 35
0
def crosscheck_operation(op, *arrays, **kw):
    
    r1 = op(*arrays, **kw)
    r2 = op(*map(lgp.StructuredArray, map(np.copy, arrays)), **kw)
    
    if not isinstance(r1, (tuple, list)):
        r1 = (r1,)
        r2 = (r2,)
    
    assert len(r1) == len(r2)
    for res1, res2 in zip(r1, r2):
    
        if isinstance(res1, lgp.StructuredArray):
            res1 = np.asarray(res1)
        if isinstance(res2, lgp.StructuredArray):
            res2 = np.asarray(res2)

        util.assert_equal(res1, res2)
Esempio n. 36
0
  def checkBalance (self, ind, spent):
    """
    Check the balance of the node with index ind.  It should be
    the initial balance minus "spent".
    """

    bal = self.nodes[ind].getbalance ()
    assert_equal (bal, initialBalance - spent)

    assert_equal (self.nodes[ind].getbalance (""), bal)
    assert_equal (self.nodes[ind].getbalance ("*"), bal)
    assert_equal (self.nodes[ind].listaccounts (), {"":bal})
Esempio n. 37
0
  def decodeNameTx (self, ind, txid):
    """
    Call the node's getrawtransaction on the txid and find the output
    that is a name operation.  Return the decoded nameop entry.
    """

    data = self.nodes[ind].getrawtransaction (txid, 1)
    res = None
    for out in data['vout']:
      if 'nameOp' in out['scriptPubKey']:
        assert res is None
        res = out['scriptPubKey']['nameOp']

        # Extra check:  Verify that the address is decoded correctly.
        addr = out['scriptPubKey']['addresses']
        assert_equal (out['scriptPubKey']['type'], "pubkeyhash")
        assert_equal (len (addr), 1)
        validation = self.nodes[ind].validateaddress (addr[0])
        assert validation['isvalid']

    assert res is not None
    return res
Esempio n. 38
0
  def checkTx (self, ind, txid, amount, fee, details):
    """
    Call 'gettransaction' and compare the result to the
    expected data given in the arguments.  "details" is an array
    containing all the tx sent/received entries expected.
    Each array element is an array itself with the fields:

      [category, nameop, amount, fee]

    nameop can be None if no "name" key is expected.
    """

    data = self.nodes[ind].gettransaction (txid)
    assert_equal (data['amount'], amount)

    if fee is None:
      assert 'fee' not in data
    else:
      assert_equal (data['fee'], fee)

    # Bring the details returned in the same format as our expected
    # argument.  Furthermore, check that each entry has an address
    # set (but don't compare the address, since we don't know it).
    detailsGot = []
    for d in data['details']:
      assert 'address' in d
      if 'name' in d:
        nameOp = d['name']
        if nameOp[:3] == 'new':
          nameOp = 'new'
      else:
        nameOp = None
      if 'fee' in d:
        fee = d['fee']
      else:
        fee = None
      detailsGot.append ([d['category'], nameOp, d['amount'], fee])

    # Compare.  Sort to get rid of differences in the order.
    detailsGot.sort ()
    details.sort ()
    assert_equal (detailsGot, details)
Esempio n. 39
0
 def run_test(self):
     for node in self.nodes:
         assert_equal(node.getblockcount(), 200)
         assert_equal(node.getbalance(), 25*10)
Esempio n. 40
0
  def run_test (self):
    NameTestFramework.run_test (self)

    # Decode name_new.
    new = self.nodes[0].name_new ("my-name")
    self.generate (0, 10)
    data = self.decodeNameTx (0, new[0])
    assert_equal (data['op'], "name_new")
    assert 'hash' in data

    # Decode name_firstupdate.
    first = self.firstupdateName (0, "my-name", new, "initial value")
    self.generate (0, 5)
    data = self.decodeNameTx (0, first)
    assert_equal (data['op'], "name_firstupdate")
    assert_equal (data['name'], "my-name")
    assert_equal (data['value'], "initial value")
    assert_equal (data['rand'], new[1])

    # Decode name_update.
    upd = self.nodes[0].name_update ("my-name", "new value")
    self.generate (0, 1)
    data = self.decodeNameTx (0, upd)
    assert_equal (data['op'], "name_update")
    assert_equal (data['name'], "my-name")
    assert_equal (data['value'], "new value")

    # Perform a rawtx name update together with an atomic currency transaction.
    # We send the test name from 0 to 1 and some coins from 1 to 0.  In other
    # words, perform an atomic name trade.

    balanceA = self.nodes[0].getbalance ()
    balanceB = self.nodes[1].getbalance ()
    price = Decimal ("1.0")

    self.atomicTrade ("my-name", "enjoy", price, 0, 1)
    self.generate (3, 1)

    data = self.checkName (3, "my-name", "enjoy", None, False)
    validate = self.nodes[1].validateaddress (data['address'])
    assert validate['ismine']
    data = self.nodes[0].name_list ("my-name")
    assert_equal (len (data), 1)
    assert_equal (data[0]['name'], "my-name")
    assert_equal (data[0]['transferred'], True)
    data = self.nodes[1].name_list ("my-name")
    assert_equal (len (data), 1)
    assert_equal (data[0]['name'], "my-name")
    assert_equal (data[0]['transferred'], False)

    # Node 0 also got a block matured.  Take this into account.
    assert_equal (balanceA + price + Decimal ("50.0"),
                  self.nodes[0].getbalance ())
    assert_equal (balanceB - price, self.nodes[1].getbalance ())
Esempio n. 41
0
  def run_test (self):
    NameTestFramework.run_test (self)

    # It would also nice to test the "initial download" error,
    # but it will only pop up if the blockchain directory (in the cache)
    # is old enough.  This can not be guaranteed (if the cache is freshly
    # generated), so that we cannot use it as a "strict" test here.
    # Instead, only warn if the test "fails".

    initialDownloadOk = True

    try:
      self.nodes[0].name_show ("a")
      initialDownloadOk = False
    except JSONRPCException as exc:
      if exc.error['code'] != -10:
        initialDownloadOk = False
    try:
      self.nodes[1].name_history ("a")
      initialDownloadOk = False
    except JSONRPCException as exc:
      if exc.error['code'] != -10:
        initialDownloadOk = False
    try:
      self.nodes[0].name_scan ()
      initialDownloadOk = False
    except JSONRPCException as exc:
      if exc.error['code'] != -10:
        initialDownloadOk = False
    try:
      self.nodes[0].name_filter ()
      initialDownloadOk = False
    except JSONRPCException as exc:
      if exc.error['code'] != -10:
        initialDownloadOk = False

    if not initialDownloadOk:
      print "WARNING: 'initial blockchain download' check failed!"
      print ("This probably means that the blockchain was regenerated"
              + " and is fine.")

    # Mine a block so that we're no longer in initial download.
    self.generate (3, 1)

    # Initially, all should be empty.
    assert_equal (self.nodes[0].name_scan (), [])
    assert_equal (self.nodes[0].name_scan ("foo", 10), [])
    assert_equal (self.nodes[0].name_filter (), [])
    assert_equal (self.nodes[0].name_filter ("", 0, 0, 0, "stat"),
                  {"blocks": 201,"count": 0})

    # Register some names with various data, heights and expiration status.
    # Using both "aa" and "b" ensures that we can also check for the expected
    # comparison order between string length and lexicographic ordering.

    newA = self.nodes[0].name_new ("a")
    newAA = self.nodes[0].name_new ("aa")
    newB = self.nodes[1].name_new ("b")
    newC = self.nodes[2].name_new ("c")
    self.generate (3, 15)

    self.firstupdateName (0, "a", newA, "wrong value")
    self.firstupdateName (0, "aa", newAA, "value aa")
    self.firstupdateName (1, "b", newB, "value b")
    self.generate (3, 15)
    self.firstupdateName (2, "c", newC, "value c")
    self.nodes[0].name_update ("a", "value a")
    self.generate (3, 20)

    # Check the expected name_scan data values.
    scan = self.nodes[3].name_scan ()
    assert_equal (len (scan), 4)
    self.checkNameData (scan[0], "a", "value a", 11, False)
    self.checkNameData (scan[1], "b", "value b", -4, True)
    self.checkNameData (scan[2], "c", "value c", 11, False)
    self.checkNameData (scan[3], "aa", "value aa", -4, True)

    # Check for expected names in various name_scan calls.
    self.checkList (self.nodes[3].name_scan (), ["a", "b", "c", "aa"])
    self.checkList (self.nodes[3].name_scan ("", 0), [])
    self.checkList (self.nodes[3].name_scan ("", -1), [])
    self.checkList (self.nodes[3].name_scan ("b"), ["b", "c", "aa"])
    self.checkList (self.nodes[3].name_scan ("zz"), [])
    self.checkList (self.nodes[3].name_scan ("", 2), ["a", "b"])
    self.checkList (self.nodes[3].name_scan ("b", 1), ["b"])

    # Check the expected name_filter data values.
    scan = self.nodes[3].name_scan ()
    assert_equal (len (scan), 4)
    self.checkNameData (scan[0], "a", "value a", 11, False)
    self.checkNameData (scan[1], "b", "value b", -4, True)
    self.checkNameData (scan[2], "c", "value c", 11, False)
    self.checkNameData (scan[3], "aa", "value aa", -4, True)

    # Check for expected names in various name_filter calls.
    height = self.nodes[3].getblockcount ()
    self.checkList (self.nodes[3].name_filter (), ["a", "b", "c", "aa"])
    self.checkList (self.nodes[3].name_filter ("[ac]"), ["a", "c", "aa"])
    self.checkList (self.nodes[3].name_filter ("", 10), [])
    self.checkList (self.nodes[3].name_filter ("", 30), ["a", "c"])
    self.checkList (self.nodes[3].name_filter ("", 0, 0, 0),
                    ["a", "b", "c", "aa"])
    self.checkList (self.nodes[3].name_filter ("", 0, 0, 1), ["a"])
    self.checkList (self.nodes[3].name_filter ("", 0, 1, 4), ["b", "c", "aa"])
    self.checkList (self.nodes[3].name_filter ("", 0, 4, 4), [])
    assert_equal (self.nodes[3].name_filter ("", 30, 0, 0, "stat"),
                  {"blocks": height, "count": 2})

    # Check test for "stat" argument.
    try:
      self.nodes[3].name_filter ("", 0, 0, 0, "string")
      raise AssertionError ("wrong check for 'stat' argument")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -8)
Esempio n. 42
0
  def run_test (self):
    NameTestFramework.run_test (self)

    # Register a name prior to forking the chain.  This is used
    # to test unrolling of updates (as opposed to registrations).
    newA = self.nodes[3].name_new ("a")
    newBshort = self.nodes[3].name_new ("b")
    newBlong = self.nodes[0].name_new ("b")
    newC = self.nodes[3].name_new ("c")
    self.generate (0, 10)
    self.firstupdateName (3, "a", newA, "initial value")
    self.generate (0, 5)

    # Split the network.
    self.split_network ()

    # Build a long chain that registers "b" (to clash with
    # the same registration on the short chain).
    self.generate (0, 2)
    self.firstupdateName (0, "b", newBlong, "b long")
    self.generate (0, 2)
    self.checkName (0, "a", "initial value", None, False)
    self.checkName (0, "b", "b long", None, False)
    self.checkNameHistory (1, "a", ["initial value"])
    self.checkNameHistory (1, "b", ["b long"])

    # Build a short chain with an update to "a" and registrations.
    self.generate (3, 1)
    txidB = self.firstupdateName (3, "b", newBshort, "b short")
    self.firstupdateName (3, "c", newC, "c registered")
    self.nodes[3].name_update ("a", "changed value")
    self.generate (3, 1)
    self.checkName (3, "a", "changed value", None, False)
    self.checkName (3, "b", "b short", None, False)
    self.checkName (3, "c", "c registered", None, False)
    self.checkNameHistory (2, "a", ["initial value", "changed value"])
    self.checkNameHistory (2, "b", ["b short"])
    self.checkNameHistory (2, "c", ["c registered"])

    # Join the network and let the long chain prevail.
    self.join_network ()
    self.checkName (3, "a", "initial value", None, False)
    self.checkName (3, "b", "b long", None, False)
    self.checkNameHistory (2, "a", ["initial value"])
    self.checkNameHistory (2, "b", ["b long"])
    try:
      self.nodes[3].name_show ("c")
      raise AssertionError ("'c' still registered after reorg")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -4)
    try:
      self.nodes[2].name_history ("c")
      raise AssertionError ("'c' still registered after reorg")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -4)

    # Mine another block.  This should at least perform the
    # non-conflicting transactions.  It is done on node 3 so
    # that these tx are actually in the mempool.
    self.generate (3, 1, False)
    self.checkName (3, "a", "changed value", None, False)
    self.checkName (3, "b", "b long", None, False)
    self.checkName (3, "c", "c registered", None, False)
    self.checkNameHistory (2, "a", ["initial value", "changed value"])
    self.checkNameHistory (2, "b", ["b long"])
    self.checkNameHistory (2, "c", ["c registered"])

    # Check that the conflicting tx got pruned from the mempool properly
    # and is marked as conflicted in the wallet.
    assert_equal (self.nodes[0].getrawmempool (), [])
    assert_equal (self.nodes[3].getrawmempool (), [])
    data = self.nodes[3].gettransaction (txidB)
    assert_equal (data['confirmations'], -1)
Esempio n. 43
0
  def run_test (self):
    NameTestFramework.run_test (self)

    assert_equal (self.nodes[0].name_list (), [])
    assert_equal (self.nodes[1].name_list (), [])

    newA = self.nodes[0].name_new ("name-a")
    newB = self.nodes[1].name_new ("name-b");
    self.generate (0, 10)
    self.firstupdateName (0, "name-a", newA, "value-a")
    self.firstupdateName (1, "name-b", newB, "value-b")
    self.generate (1, 5)

    arr = self.nodes[0].name_list ()
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-a", "value-a", False, False)
    arr = self.nodes[1].name_list ()
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-b", "value-b", False, False)

    assert_equal (self.nodes[0].name_list ("name-b"), [])
    assert_equal (self.nodes[1].name_list ("name-a"), [])

    # Transfer a name away and check that name_list updates accordingly.

    addrB = self.nodes[1].getnewaddress ()
    self.nodes[0].name_update ("name-a", "enjoy", addrB)
    arr = self.nodes[0].name_list ()
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-a", "value-a", False, False)

    self.generate (0, 1)
    arr = self.nodes[0].name_list ()
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-a", "enjoy", False, True)
    arr = self.nodes[1].name_list ()
    assert_equal (len (arr), 2)
    self.checkNameStatus (arr[0], "name-a", "enjoy", False, False)
    self.checkNameStatus (arr[1], "name-b", "value-b", False, False)

    # Updating the name in the new wallet shouldn't change the
    # old wallet's name_list entry.
    self.nodes[1].name_update ("name-a", "new value")
    self.generate (0, 1)
    arr = self.nodes[0].name_list ()
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-a", "enjoy", False, True)
    arr = self.nodes[1].name_list ("name-a")
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-a", "new value", False, False)

    # Transfer it back and see that it updates in wallet A.
    addrA = self.nodes[0].getnewaddress ()
    self.nodes[1].name_update ("name-a", "sent", addrA)
    self.generate (0, 1)
    arr = self.nodes[0].name_list ()
    assert_equal (len (arr), 1)
    self.checkNameStatus (arr[0], "name-a", "sent", False, False)

    # Let name-b expire.
    self.generate (0, 25)
    arr = self.nodes[1].name_list ()
    assert_equal (len (arr), 2)
    self.checkNameStatus (arr[0], "name-a", "sent", False, True)
    self.checkNameStatus (arr[1], "name-b", "value-b", True, False)
Esempio n. 44
0
    def run_test(self):
        MonetaTestFramework.run_test(self)

        tips = self.nodes[0].getchaintips()
        assert_equal(len(tips), 1)
        assert_equal(tips[0]["branchlen"], 0)
        assert_equal(tips[0]["height"], 200)
        assert_equal(tips[0]["status"], "active")

        # Split the network and build two chains of different lengths.
        self.split_network()
        self.nodes[0].setgenerate(True, 10)
        self.nodes[2].setgenerate(True, 20)
        self.sync_all()

        tips = self.nodes[1].getchaintips()
        assert_equal(len(tips), 1)
        shortTip = tips[0]
        assert_equal(shortTip["branchlen"], 0)
        assert_equal(shortTip["height"], 210)
        assert_equal(tips[0]["status"], "active")

        tips = self.nodes[3].getchaintips()
        assert_equal(len(tips), 1)
        longTip = tips[0]
        assert_equal(longTip["branchlen"], 0)
        assert_equal(longTip["height"], 220)
        assert_equal(tips[0]["status"], "active")

        # Join the network halves and check that we now have two tips
        # (at least at the nodes that previously had the short chain).
        self.join_network()

        tips = self.nodes[0].getchaintips()
        assert_equal(len(tips), 2)
        assert_equal(tips[0], longTip)

        assert_equal(tips[1]["branchlen"], 10)
        assert_equal(tips[1]["status"], "valid-fork")
        tips[1]["branchlen"] = 0
        tips[1]["status"] = "active"
        assert_equal(tips[1], shortTip)
Esempio n. 45
0
  def run_test (self):
    NameTestFramework.run_test (self)

    # Construct a 2-of-2 multisig address shared between two nodes.
    pubkeyA = self.getNewPubkey (0)
    pubkeyB = self.getNewPubkey (1)
    p2sh = self.nodes[0].addmultisigaddress (2, [pubkeyA, pubkeyB])
    p2sh_ = self.nodes[1].addmultisigaddress (2, [pubkeyA, pubkeyB])
    assert_equal (p2sh, p2sh_)

    # Register a new name to that address.
    new = self.nodes[0].name_new ("name")
    self.generate (0, 10)
    self.firstupdateName (0, "name", new, "value", p2sh)
    self.generate (1, 5)
    data = self.checkName (2, "name", "value", None, False)
    assert_equal (data['address'], p2sh)

    # Straight-forward name updating should fail (for both nodes).
    try:
      self.nodes[0].name_update ("name", "new value")
      raise AssertionError ("name_update allowed from single node")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -4)
    try:
      self.nodes[1].name_update ("name", "new value")
      raise AssertionError ("name_update allowed from single node")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -4)

    # Find some other input to add as fee.
    unspents = self.nodes[0].listunspent ()
    assert len (unspents) > 0
    feeInput = unspents[0]
    changeAddr = self.nodes[0].getnewaddress ()
    changeAmount = feeInput['amount'] - Decimal ("0.01")

    # Construct the name update as raw transaction.
    addr = self.nodes[2].getnewaddress ()
    inputs = [{"txid": data['txid'], "vout": data['vout']}, feeInput]
    outputs = {changeAddr: changeAmount}
    op = {"op": "name_update", "name": "name",
          "value": "it worked", "address": addr}
    txRaw = self.nodes[3].createrawtransaction (inputs, outputs, op)

    # Sign it partially.
    partial = self.nodes[0].signrawtransaction (txRaw)
    assert not partial['complete']
    try:
      self.nodes[2].sendrawtransaction (partial['hex'])
      raise AssertionError ("incomplete transaction accepted")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -26)

    # Sign it fully and transmit it.
    signed = self.nodes[1].signrawtransaction (partial['hex'])
    assert signed['complete']
    tx = signed['hex']

    # Manipulate the signature to invalidate it.  This checks whether or
    # not the OP_MULTISIG is actually verified (vs just the script hash
    # compared to the redeem script).
    txData = bytearray (binascii.unhexlify (tx))
    txData[44] = (txData[44] + 10) % 256
    txManipulated = binascii.hexlify (txData)

    # Send the tx.  The manipulation should be caught (independently of
    # when strict P2SH checks are enabled, since they are enforced
    # mandatorily in the mempool).
    try:
      self.nodes[2].sendrawtransaction (txManipulated)
      raise AssertionError ("manipulated signature tx accepted")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -26)
    self.nodes[2].sendrawtransaction (tx)
    self.generate (3, 1)

    # Check that it was transferred correctly.
    self.checkName (3, "name", "it worked", None, False)
    self.nodes[2].name_update ("name", "changed")
    self.generate (3, 1)
    self.checkName (3, "name", "changed", None, False)
Esempio n. 46
0
 def run_test (self, nodes):
     res = nodes[0].getchaintips ()
     assert_equal (len (res), 1)
     res = res[0]
     assert_equal (res['branchlen'], 0)
     assert_equal (res['height'], 200)
Esempio n. 47
0
  def run_test (self):
    BitcoinTestFramework.run_test (self)

    # Generate a block so that we are not "downloading blocks".
    self.nodes[0].setgenerate (True, 1)

    # Compare basic data of getauxblock to getblocktemplate.
    auxblock = self.nodes[0].getauxblock ()
    blocktemplate = self.nodes[0].getblocktemplate ()
    assert_equal (auxblock['coinbasevalue'], blocktemplate['coinbasevalue'])
    assert_equal (auxblock['bits'], blocktemplate['bits'])
    assert_equal (auxblock['height'], blocktemplate['height'])
    assert_equal (auxblock['previousblockhash'], blocktemplate['previousblockhash'])

    # Compare target and take byte order into account.
    target = auxblock['_target']
    reversedTarget = auxpow.reverseHex (target)
    assert_equal (reversedTarget, blocktemplate['target'])

    # Verify data that can be found in another way.
    assert_equal (auxblock['chainid'], 1)
    assert_equal (auxblock['height'], self.nodes[0].getblockcount () + 1)
    assert_equal (auxblock['previousblockhash'], self.nodes[0].getblockhash (auxblock['height'] - 1))

    # Calling again should give the same block.
    auxblock2 = self.nodes[0].getauxblock ()
    assert_equal (auxblock2, auxblock)

    # If we receive a new block, the old hash will be replaced.
    self.sync_all ()
    self.nodes[1].setgenerate (True, 1)
    self.sync_all ()
    auxblock2 = self.nodes[0].getauxblock ()
    assert auxblock['hash'] != auxblock2['hash']
    try:
      self.nodes[0].getauxblock (auxblock['hash'], "x")
      raise AssertionError ("invalid block hash accepted")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -8)

    # Invalid format for auxpow.
    try:
      self.nodes[0].getauxblock (auxblock2['hash'], "x")
      raise AssertionError ("malformed auxpow accepted")
    except JSONRPCException as exc:
      assert_equal (exc.error['code'], -1)

    # Invalidate the block again, send a transaction and query for the
    # auxblock to solve that contains the transaction.
    self.nodes[0].setgenerate (True, 1)
    addr = self.nodes[1].getnewaddress ()
    txid = self.nodes[0].sendtoaddress (addr, 1)
    self.sync_all ()
    assert_equal (self.nodes[1].getrawmempool (), [txid])
    auxblock = self.nodes[0].getauxblock ()
    blocktemplate = self.nodes[0].getblocktemplate ()
    target = blocktemplate['target']

    # Compute invalid auxpow.
    apow = auxpow.computeAuxpow (auxblock['hash'], target, False)
    res = self.nodes[0].getauxblock (auxblock['hash'], apow)
    assert not res

    # Compute and submit valid auxpow.
    apow = auxpow.computeAuxpow (auxblock['hash'], target, True)
    res = self.nodes[0].getauxblock (auxblock['hash'], apow)
    assert res

    # Make sure that the block is indeed accepted.
    self.sync_all ()
    assert_equal (self.nodes[1].getrawmempool (), [])
    height = self.nodes[1].getblockcount ()
    assert_equal (height, auxblock['height'])
    assert_equal (self.nodes[1].getblockhash (height), auxblock['hash'])

    # Check that it paid correctly to the first node.
    t = self.nodes[0].listtransactions ("", 1)
    assert_equal (len (t), 1)
    t = t[0]
    assert_equal (t['category'], "immature")
    assert_equal (t['blockhash'], auxblock['hash'])
    assert t['generated']
    assert t['amount'] >= Decimal ("25")
    assert_equal (t['confirmations'], 1)

    # Verify the coinbase script.  Ensure that it includes the block height
    # to make the coinbase tx unique.  The expected block height is around
    # 200, so that the serialisation of the CScriptNum ends in an extra 00.
    # The vector has length 2, which makes up for 02XX00 as the serialised
    # height.  Check this.
    blk = self.nodes[1].getblock (auxblock['hash'])
    tx = self.nodes[1].getrawtransaction (blk['tx'][0], 1)
    coinbase = tx['vin'][0]['coinbase']
    assert_equal ("02%02x00" % auxblock['height'], coinbase[0 : 6])
Esempio n. 48
0
    def run_test (self):
        BitcoinTestFramework.run_test (self)

        tips = self.nodes[0].getchaintips ()
        assert_equal (len (tips), 1)
        assert_equal (tips[0]['branchlen'], 0)
        assert_equal (tips[0]['height'], 200)

        # Split the network and build two chains of different lengths.
        self.split_network ()
        self.nodes[0].setgenerate (True, 10);
        self.nodes[2].setgenerate (True, 20);
        self.sync_all ()

        tips = self.nodes[1].getchaintips ()
        assert_equal (len (tips), 1)
        shortTip = tips[0]
        assert_equal (shortTip['branchlen'], 0)
        assert_equal (shortTip['height'], 210)

        tips = self.nodes[3].getchaintips ()
        assert_equal (len (tips), 1)
        longTip = tips[0]
        assert_equal (longTip['branchlen'], 0)
        assert_equal (longTip['height'], 220)

        # Join the network halves and check that we now have two tips
        # (at least at the nodes that previously had the short chain).
        self.join_network ()

        tips = self.nodes[0].getchaintips ()
        assert_equal (len (tips), 2)
        assert_equal (tips[0], longTip)

        assert_equal (tips[1]['branchlen'], 10)
        tips[1]['branchlen'] = 0;
        assert_equal (tips[1], shortTip)
Esempio n. 49
0
  def run_test (self):
    NameTestFramework.run_test (self)

    # Start the registration of two names which will be used.  name-long
    # will expire and be reregistered on the short chain, which will be
    # undone with the reorg.  name-short will be updated before expiration
    # on the short chain, but this will be rerolled and the name expire
    # instead on the long chain.  Check that the mempool and the UTXO set
    # behave as they should.
    newLong = self.nodes[0].name_new ("name-long")
    newLong2 = self.nodes[3].name_new ("name-long")
    newShort = self.nodes[3].name_new ("name-short")
    self.generate (1, 12)

    # Register the names.  name-long should expire one block before
    # name-short, so that the situation described above works out.
    updLong = self.firstupdateName (0, "name-long", newLong, "value")
    self.generate (1, 2)
    updShort = self.firstupdateName (3, "name-short", newShort, "value")
    self.generate (1, 27)
    self.checkName (1, "name-long", "value", 2, False)
    self.checkName (1, "name-short", "value", 4, False)

    # Check that the UTXO entries are there.
    self.checkUTXO (1, "name-long", True)
    self.checkUTXO (1, "name-short", True)

    # Split the network.
    self.split_network ()

    # Let name-long expire on the short chain.
    self.generate (2, 2)
    self.checkName (2, "name-long", "value", 0, True)
    self.checkName (2, "name-short", "value", 2, False)
    self.checkUTXO (2, "name-long", False)
    self.checkUTXO (2, "name-short", True)

    # Snatch up name-long and update name-short just-in-time.  Note that
    # "just-in-time" is "expires_in == 2", since when creating the block,
    # it will be "expires_in == 1" already!
    updLong2 = self.firstupdateName (3, "name-long", newLong2, "value 2")
    renewShort = self.nodes[3].name_update ("name-short", "renewed")
    self.generate (2, 1)
    self.checkName (2, "name-long", "value 2", 30, False)
    self.checkName (2, "name-short", "renewed", 30, False)
    self.checkNameHistory (2, "name-long", ["value", "value 2"])
    self.checkNameHistory (2, "name-short", ["value", "renewed"])

    # Create a longer chain on the other part of the network.  Let name-short
    # expire there but renew name-long instead.
    self.nodes[0].name_update ("name-long", "renewed")
    self.generate (1, 5)
    self.checkName (1, "name-long", "renewed", 26, False)
    self.checkName (1, "name-short", "value", -1, True)
    self.checkNameHistory (1, "name-long", ["value", "renewed"])
    self.checkNameHistory (1, "name-short", ["value"])
    self.checkUTXO (1, "name-long", True)
    self.checkUTXO (1, "name-short", False)

    # Join the network and let the long chain prevail.  This should
    # completely revoke all changes on the short chain, including
    # the mempool (since all tx there are conflicts with name expirations).
    assert self.nodes[1].getblockcount () > self.nodes[2].getblockcount ()
    self.join_network ()

    # Test the expected situation of the long chain.
    self.checkName (2, "name-long", "renewed", 26, False)
    self.checkName (2, "name-short", "value", -1, True)
    self.checkNameHistory (2, "name-long", ["value", "renewed"])
    self.checkNameHistory (2, "name-short", ["value"])
    self.checkUTXO (2, "name-long", True)
    self.checkUTXO (2, "name-short", False)

    # Check that the conflicting tx's are marked in the wallet
    # as conflicts and that they got removed from the mempool.
    assert_equal (self.nodes[0].getrawmempool (), [])
    assert_equal (self.nodes[3].getrawmempool (), [])
    data = self.nodes[3].gettransaction (updLong2)
    assert_equal (data['confirmations'], -1)
    data = self.nodes[3].gettransaction (renewShort)
    assert_equal (data['confirmations'], -1)