Esempio n. 1
0
// returns the lowers possible price with which a tx was or could have been included
func (self *GasPriceOracle) lowestPrice(block *types.Block) *big.Int {
	gasUsed := big.NewInt(0)

	receipts := core.GetBlockReceipts(self.eth.ChainDb(), block.Hash())
	if len(receipts) > 0 {
		if cgu := receipts[len(receipts)-1].CumulativeGasUsed; cgu != nil {
			gasUsed = receipts[len(receipts)-1].CumulativeGasUsed
		}
	}

	if new(big.Int).Mul(gasUsed, big.NewInt(100)).Cmp(new(big.Int).Mul(block.GasLimit(),
		big.NewInt(int64(self.eth.GpoFullBlockRatio)))) < 0 {
		// block is not full, could have posted a tx with MinGasPrice
		return big.NewInt(0)
	}

	txs := block.Transactions()
	if len(txs) == 0 {
		return big.NewInt(0)
	}
	// block is full, find smallest gasPrice
	minPrice := txs[0].GasPrice()
	for i := 1; i < len(txs); i++ {
		price := txs[i].GasPrice()
		if price.Cmp(minPrice) < 0 {
			minPrice = price
		}
	}
	return minPrice
}
Esempio n. 2
0
func factorial(x *big.Int) *big.Int {
	n := big.NewInt(1)
	if x.Cmp(big.NewInt(0)) == 0 {
		return n
	}
	return n.Mul(x, factorial(n.Sub(x, n)))
}
Esempio n. 3
0
// Lagrangian interpolation to reconstruct the constant factor for a polynomial
func Interpolate(shares *[]int64, shareAvailable *[]bool, nshare int32, prime *big.Int) int64 {
	primebig := big.NewInt(0)
	primebig.Set(prime)
	resultbig := big.NewInt(0)
	for share := int32(0); share < nshare; share++ {
		if (*shareAvailable)[share] {
			numerator := big.NewInt(1)
			denominator := big.NewInt(1)
			for otherShare := int32(0); otherShare < nshare; otherShare++ {
				if (otherShare == share) || (!(*shareAvailable)[otherShare]) {
					continue
				}
				numerator.Mul(numerator, big.NewInt(-1*int64(otherShare+2)))
				denominator.Mul(denominator, big.NewInt(int64(share-otherShare)))
			}
			lagrange := big.NewInt(1)
			lagrange.DivMod(numerator, denominator, primebig)
			primebig.Set(prime) // Strangely divmod sets primebig to 0, divmod bad
			tmp := big.NewInt(1)
			tmp.Mul(big.NewInt((*shares)[share]), lagrange)
			resultTmp := big.NewInt(0)
			resultTmp.Add(tmp, resultbig)
			resultbig.Mod(resultTmp, primebig)
		}
	}
	return resultbig.Int64()
}
func TestInvalidTransactions(t *testing.T) {
	pool, key := setupTxPool()

	tx := transaction(0, big.NewInt(100), key)
	if err := pool.Add(tx); err != ErrNonExistentAccount {
		t.Error("expected", ErrNonExistentAccount)
	}

	from, _ := tx.From()
	pool.currentState().AddBalance(from, big.NewInt(1))
	if err := pool.Add(tx); err != ErrInsufficientFunds {
		t.Error("expected", ErrInsufficientFunds)
	}

	balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice()))
	pool.currentState().AddBalance(from, balance)
	if err := pool.Add(tx); err != ErrIntrinsicGas {
		t.Error("expected", ErrIntrinsicGas, "got", err)
	}

	pool.currentState().SetNonce(from, 1)
	pool.currentState().AddBalance(from, big.NewInt(0xffffffffffffff))
	tx = transaction(0, big.NewInt(100000), key)
	if err := pool.Add(tx); err != ErrNonce {
		t.Error("expected", ErrNonce)
	}
}
Esempio n. 5
0
func (table HashTable) GetRecordByHashedString(
	input string, hashTTL time.Duration,
) ([]byte, error) {
	hash := sha256.Sum256([]byte(
		fmt.Sprintf("%s%d", input, table.getTimeHashPart(hashTTL))),
	)

	hashMaxLength := int64(1)
	index := int64(0)

	for _, hashByte := range hash {
		if hashMaxLength > table.Count {
			break
		}

		hashMaxLength <<= 8
		index += hashMaxLength * int64(hashByte)
	}

	remainder := big.NewInt(0).Mod(
		big.NewInt(index), big.NewInt(table.Count),
	).Int64()

	return table.GetRecord(remainder)
}
func TestTransactionChainFork(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
	resetState := func() {
		db, _ := ethdb.NewMemDatabase()
		statedb, _ := state.New(common.Hash{}, db)
		pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
		currentState, _ := pool.currentState()
		currentState.AddBalance(addr, big.NewInt(100000000000000))
		pool.resetState()
	}
	resetState()

	tx := transaction(0, big.NewInt(100000), key)
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
	pool.RemoveTransactions([]*types.Transaction{tx})

	// reset the pool's internal state
	resetState()
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
}
func TestRemoveTx(t *testing.T) {
	pool, key := setupTxPool()
	tx := transaction(0, big.NewInt(100), key)
	from, _ := tx.From()
	pool.currentState().AddBalance(from, big.NewInt(1))
	pool.queueTx(tx.Hash(), tx)
	pool.addTx(tx.Hash(), from, tx)
	if len(pool.queue) != 1 {
		t.Error("expected queue to be 1, got", len(pool.queue))
	}

	if len(pool.pending) != 1 {
		t.Error("expected txs to be 1, got", len(pool.pending))
	}

	pool.removeTx(tx.Hash())

	if len(pool.queue) > 0 {
		t.Error("expected queue to be 0, got", len(pool.queue))
	}

	if len(pool.pending) > 0 {
		t.Error("expected txs to be 0, got", len(pool.pending))
	}
}
Esempio n. 8
0
func plus(z *big.Int, x *big.Int, y *big.Int) *big.Int {
	var lim big.Int
	lim.Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
	z.Add(x, y)
	return z.Mod(z, &lim)

}
Esempio n. 9
0
File: srp.go Progetto: regorov/go
func NewSRPConnection(C []byte, P []byte, H hash.Hash) (srp *SRPConnection, err error) {
	secretBytes := make([]byte, 32)
	_, err = crand.Reader.Read(secretBytes)
	if err != nil {
		return nil, err
	}

	secretHex := hex.EncodeToString(secretBytes)
	a, ok := big.NewInt(0).SetString(secretHex, 16)
	if !ok {
		return nil, fmt.Errorf("Could not initialise SRP a")
	}

	A := big.NewInt(0).Exp(g, a, n)

	srp = &SRPConnection{
		C: C,
		P: P,
		H: H,
		a: a,
		A: A,
	}

	return srp, nil
}
Esempio n. 10
0
// Full STS communication example illustrated with two concurrent Go routines agreeing on a master key.
func Example_usage() {
	// STS cyclic group parameters, global for the app (small examples, not secure!)
	group := big.NewInt(3910779947)
	generator := big.NewInt(1213725007)

	// STS encryption parameters
	cipher := aes.NewCipher
	bits := 128
	hash := crypto.SHA1

	// RSA key-pairs for the communicating parties, obtained from somewhere else (no error checks)
	iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
	accKey, _ := rsa.GenerateKey(rand.Reader, 1024)

	// Start two Go routines: one initiator and one acceptor communicating on a channel
	transport := make(chan []byte)
	iniOut := make(chan []byte)
	accOut := make(chan []byte)

	go initiator(group, generator, cipher, bits, hash, iniKey, &accKey.PublicKey, transport, iniOut)
	go acceptor(group, generator, cipher, bits, hash, accKey, &iniKey.PublicKey, transport, accOut)

	// Check that the parties agreed upon the same master key
	iniMaster, iniOk := <-iniOut
	accMaster, accOk := <-accOut

	fmt.Printf("Initiator key valid: %v\n", iniOk && iniMaster != nil)
	fmt.Printf("Acceptor key valid: %v\n", accOk && accMaster != nil)
	fmt.Printf("Keys match: %v\n", bytes.Equal(iniMaster, accMaster))

	// Output:
	// Initiator key valid: true
	// Acceptor key valid: true
	// Keys match: true
}
Esempio n. 11
0
// exponential computes exp(x) using the Taylor series. It converges quickly
// since we call it with only small values of x.
func exponential(x *big.Float) *big.Float {
	// The Taylor series for e**x, exp(x), is 1 + x + x²/2! + x³/3! ...

	xN := newF().Set(x)
	term := newF()
	n := big.NewInt(1)
	nFactorial := big.NewInt(1)
	z := newF().SetInt64(1)

	loop := newLoop("exponential", x, 4)
	for i := 0; ; i++ {
		term.Set(xN)
		nf := newF().SetInt(nFactorial)
		term.Quo(term, nf)
		z.Add(z, term)

		if loop.terminate(z) {
			break
		}
		// Advance x**index (multiply by x).
		xN.Mul(xN, x)
		// Advance n, n!.
		n.Add(n, bigOne.Int)
		nFactorial.Mul(nFactorial, n)
	}

	return z

}
Esempio n. 12
0
func newDSAPublicKeyFromJSON(s []byte) (*dsaPublicKey, error) {
	dsakey := new(dsaPublicKey)
	dsajson := new(dsaPublicKeyJSON)
	var err error
	err = json.Unmarshal([]byte(s), &dsajson)
	if err != nil {
		return nil, err
	}
	if !T_DSA_PUB.isAcceptableSize(dsajson.Size) {
		return nil, ErrInvalidKeySize
	}
	b, err := decodeWeb64String(dsajson.Y)
	if err != nil {
		return nil, ErrBase64Decoding
	}
	dsakey.key.Y = big.NewInt(0).SetBytes(b)
	b, err = decodeWeb64String(dsajson.G)
	if err != nil {
		return nil, ErrBase64Decoding
	}
	dsakey.key.G = big.NewInt(0).SetBytes(b)
	b, err = decodeWeb64String(dsajson.P)
	if err != nil {
		return nil, ErrBase64Decoding
	}
	dsakey.key.P = big.NewInt(0).SetBytes(b)
	b, err = decodeWeb64String(dsajson.Q)
	if err != nil {
		return nil, ErrBase64Decoding
	}
	dsakey.key.Q = big.NewInt(0).SetBytes(b)
	return dsakey, nil
}
Esempio n. 13
0
func TestScan(t *testing.T) {
	// Define some local constants
	over1, _ := net.ResolveTCPAddr("tcp", "127.0.0.3:33333")
	over2, _ := net.ResolveTCPAddr("tcp", "127.0.0.5:55555")
	ipnet1 := &net.IPNet{
		IP:   over1.IP,
		Mask: over1.IP.DefaultMask(),
	}
	ipnet2 := &net.IPNet{
		IP:   over2.IP,
		Mask: over2.IP.DefaultMask(),
	}
	// Start up two bootstrappers
	bs1, evs1, err := New(ipnet1, []byte("magic"), big.NewInt(1), over1.Port)
	if err != nil {
		t.Fatalf("failed to create first booter: %v.", err)
	}
	if err := bs1.Boot(); err != nil {
		t.Fatalf("failed to boot first booter: %v.", err)
	}
	defer bs1.Terminate()

	bs2, evs2, err := New(ipnet2, []byte("magic"), big.NewInt(2), over2.Port)
	if err != nil {
		t.Fatalf("failed to create second booter: %v.", err)
	}
	if err := bs2.Boot(); err != nil {
		t.Fatalf("failed to boot second booter: %v.", err)
	}
	defer bs2.Terminate()

	// Wait and make sure they found each other and not themselves
	e1, e2 := <-evs1, <-evs2
	if !e1.Addr.IP.Equal(over2.IP) || e1.Addr.Port != over2.Port {
		t.Fatalf("invalid address on first booter: have %v, want %v.", e1.Addr, over2)
	}
	if !e2.Addr.IP.Equal(over1.IP) || e2.Addr.Port != over1.Port {
		t.Fatalf("invalid address on second booter: have %v, want %v.", e2.Addr, over1)
	}

	// Each should report twice (foreign request + foreign response to local request)
	e1, e2 = <-evs1, <-evs2
	if !e1.Addr.IP.Equal(over2.IP) || e1.Addr.Port != over2.Port {
		t.Fatalf("invalid address on first booter: have %v, want %v.", e1.Addr, over2)
	}
	if !e2.Addr.IP.Equal(over1.IP) || e2.Addr.Port != over1.Port {
		t.Fatalf("invalid address on second booter: have %v, want %v.", e2.Addr, over1)
	}

	// Further beats shouldn't arrive (unless the probing catches us, should be rare)
	timeout := time.Tick(250 * time.Millisecond)
	select {
	case <-timeout:
		// Do nothing
	case a := <-evs1:
		t.Fatalf("extra address on first booter: %v.", a)
	case a := <-evs2:
		t.Fatalf("extra address on second booter: %v.", a)
	}
}
Esempio n. 14
0
func init() {
	jwk1 = jose.JWK{
		ID:       "1",
		Type:     "RSA",
		Alg:      "RS256",
		Use:      "sig",
		Modulus:  big.NewInt(1),
		Exponent: 65537,
	}

	jwk2 = jose.JWK{
		ID:       "2",
		Type:     "RSA",
		Alg:      "RS256",
		Use:      "sig",
		Modulus:  big.NewInt(2),
		Exponent: 65537,
	}

	jwk3 = jose.JWK{
		ID:       "3",
		Type:     "RSA",
		Alg:      "RS256",
		Use:      "sig",
		Modulus:  big.NewInt(3),
		Exponent: 65537,
	}
}
Esempio n. 15
0
File: upload.go Progetto: bfix/sid
func InitDocumentHandler(defs UploadDefs) {

	// initialize upload handling parameters
	uploadPath = defs.Path
	treshold = defs.ShareTreshold

	// check for disabled secret sharing scheme
	if treshold > 0 {
		// compute prime: (2^512-1) - SharePrimeOfs
		one := big.NewInt(1)
		ofs := big.NewInt(int64(defs.SharePrimeOfs))
		prime = new(big.Int).Lsh(one, 512)
		prime = new(big.Int).Sub(prime, one)
		prime = new(big.Int).Sub(prime, ofs)

		// open keyring file
		rdr, err := os.Open(defs.Keyring)
		if err != nil {
			// can't read keys -- terminate!
			logger.Printf(logger.ERROR, "[sid.upload] Can't read keyring file '%s' -- terminating!\n", defs.Keyring)
			os.Exit(1)
		}
		defer rdr.Close()

		// read public keys from keyring
		if reviewer, err = openpgp.ReadKeyRing(rdr); err != nil {
			// can't read keys -- terminate!
			logger.Printf(logger.ERROR, "[sid.upload] Failed to process keyring '%s' -- terminating!\n", defs.Keyring)
			os.Exit(1)
		}
	} else {
		logger.Printf(logger.WARN, "[sid.upload] Secret sharing scheme disabled -- uploads will be stored unencrypted!!")
	}
}
Esempio n. 16
0
// CreateCertificate requests the creation of a new enrollment certificate by the TLSCA.
//
func (tlscap *TLSCAP) CreateCertificate(ctx context.Context, in *pb.TLSCertCreateReq) (*pb.TLSCertCreateResp, error) {
	Trace.Println("grpc TLSCAP:CreateCertificate")

	id := in.Id.Id

	sig := in.Sig
	in.Sig = nil

	r, s := big.NewInt(0), big.NewInt(0)
	r.UnmarshalText(sig.R)
	s.UnmarshalText(sig.S)

	raw := in.Pub.Key
	if in.Pub.Type != pb.CryptoType_ECDSA {
		return nil, errors.New("unsupported key type")
	}
	pub, err := x509.ParsePKIXPublicKey(in.Pub.Key)
	if err != nil {
		return nil, err
	}

	hash := utils.NewHash()
	raw, _ = proto.Marshal(in)
	hash.Write(raw)
	if ecdsa.Verify(pub.(*ecdsa.PublicKey), hash.Sum(nil), r, s) == false {
		return nil, errors.New("signature does not verify")
	}

	if raw, err = tlscap.tlsca.createCertificate(id, pub.(*ecdsa.PublicKey), x509.KeyUsageDigitalSignature, in.Ts.Seconds, nil); err != nil {
		Error.Println(err)
		return nil, err
	}

	return &pb.TLSCertCreateResp{&pb.Cert{raw}, &pb.Cert{tlscap.tlsca.raw}}, nil
}
Esempio n. 17
0
func TestMinusConst(t *testing.T) {
	cases := []struct {
		a   *big.Int
		ans Poly
	}{
		{
			big.NewInt(1),
			NewPolyInts(-1, 1),
		},
		{
			big.NewInt(-8),
			NewPolyInts(8, 1),
		},
		{
			big.NewInt(54321),
			NewPolyInts(-54321, 1),
		},
	}
	for _, c := range cases {
		res := xMinusConst(c.a)
		if res.Compare(&c.ans) != 0 {
			t.Errorf("(x-a) from %v != %v (your answer was %v)", c.a, c.ans, res)
		}
	}
}
Esempio n. 18
0
func (num *Amount) Divide(den *Amount) (*Amount, error) {
	if den.IsZero() {
		return nil, fmt.Errorf("Division by zero")
	}
	if num.IsZero() {
		return num.ZeroClone(), nil
	}
	av, bv := num.Num, den.Num
	ao, bo := num.Offset, den.Offset
	if num.Native {
		for ; av < minValue; av *= 10 {
			ao--
		}
	}
	if den.Native {
		for ; bv < minValue; bv *= 10 {
			bo--
		}
	}
	// Compute (numerator * 10^17) / denominator
	d := big.NewInt(0).SetUint64(av)
	d.Mul(d, bigTenTo17)
	d.Div(d, big.NewInt(0).SetUint64(bv))
	// 10^16 <= quotient <= 10^18
	if len(d.Bytes()) > 64 {
		return nil, fmt.Errorf("Divide: %s/%s", num.Debug(), den.Debug())
	}
	v := NewValue(num.Native, num.Negative != den.Negative, d.Uint64()+5, ao-bo-17)
	c := newAmount(v, num.Currency, num.Issuer)
	return c, c.canonicalise()
}
// Tests that if the transaction count belonging to a single account goes above
// some threshold, the higher transactions are dropped to prevent DOS attacks.
func TestTransactionQueueLimiting(t *testing.T) {
	// Create a test account and fund it
	pool, key := setupTxPool()
	account, _ := transaction(0, big.NewInt(0), key).From()

	state, _ := pool.currentState()
	state.AddBalance(account, big.NewInt(1000000))

	// Keep queuing up transactions and make sure all above a limit are dropped
	for i := uint64(1); i <= maxQueued+5; i++ {
		if err := pool.Add(transaction(i, big.NewInt(100000), key)); err != nil {
			t.Fatalf("tx %d: failed to add transaction: %v", i, err)
		}
		if len(pool.pending) != 0 {
			t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0)
		}
		if i <= maxQueued {
			if len(pool.queue[account]) != int(i) {
				t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, len(pool.queue[account]), i)
			}
		} else {
			if len(pool.queue[account]) != maxQueued {
				t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, len(pool.queue[account]), maxQueued)
			}
		}
	}
}
Esempio n. 20
0
func (v *Value) String() string {
	if v.IsZero() {
		return "0"
	}
	if v.Native && v.IsScientific() {
		value := strconv.FormatUint(v.Num, 10)
		offset := strconv.FormatInt(v.Offset, 10)
		if v.Negative {
			return "-" + value + "e" + offset
		}
		return value + "e" + offset
	}
	value := big.NewInt(int64(v.Num))
	if v.Negative {
		value.Neg(value)
	}
	var offset *big.Int
	if v.Native {
		offset = big.NewInt(-6)
	} else {
		offset = big.NewInt(v.Offset)
	}
	exp := offset.Exp(bigTen, offset.Neg(offset), nil)
	rat := big.NewRat(0, 1).SetFrac(value, exp)
	left := rat.FloatString(0)
	if rat.IsInt() {
		return left
	}
	length := len(left)
	if v.Negative {
		length -= 1
	}
	return strings.TrimRight(rat.FloatString(32-length), "0")
}
func TestTransactionDoubleNonce(t *testing.T) {
	pool, key := setupTxPool()
	addr := crypto.PubkeyToAddress(key.PublicKey)
	resetState := func() {
		db, _ := ethdb.NewMemDatabase()
		statedb := state.New(common.Hash{}, db)
		pool.currentState = func() *state.StateDB { return statedb }
		pool.currentState().AddBalance(addr, big.NewInt(100000000000000))
		pool.resetState()
	}
	resetState()

	tx := transaction(0, big.NewInt(100000), key)
	tx2 := transaction(0, big.NewInt(1000000), key)
	if err := pool.add(tx); err != nil {
		t.Error("didn't expect error", err)
	}
	if err := pool.add(tx2); err != nil {
		t.Error("didn't expect error", err)
	}

	pool.checkQueue()
	if len(pool.pending) != 2 {
		t.Error("expected 2 pending txs. Got", len(pool.pending))
	}
}
Esempio n. 22
0
func TestValueTypes(t *testing.T) {
	str := NewValue("str")
	num := NewValue(1)
	inter := NewValue([]interface{}{1})
	byt := NewValue([]byte{1, 2, 3, 4})
	bigInt := NewValue(big.NewInt(10))

	if str.Str() != "str" {
		t.Errorf("expected Str to return 'str', got %s", str.Str())
	}

	if num.Uint() != 1 {
		t.Errorf("expected Uint to return '1', got %d", num.Uint())
	}

	interExp := []interface{}{1}
	if !NewValue(inter.Interface()).Cmp(NewValue(interExp)) {
		t.Errorf("expected Interface to return '%v', got %v", interExp, num.Interface())
	}

	bytExp := []byte{1, 2, 3, 4}
	if bytes.Compare(byt.Bytes(), bytExp) != 0 {
		t.Errorf("expected Bytes to return '%v', got %v", bytExp, byt.Bytes())
	}

	bigExp := big.NewInt(10)
	if bigInt.BigInt().Cmp(bigExp) != 0 {
		t.Errorf("expected BigInt to return '%v', got %v", bigExp, bigInt.BigInt())
	}
}
Esempio n. 23
0
// CompactToBig converts a compact representation of a whole number N to an
// unsigned 32-bit number.  The representation is similar to IEEE754 floating
// point numbers.
//
// Like IEEE754 floating point, there are three basic components: the sign,
// the exponent, and the mantissa.  They are broken out as follows:
//
//	* the most significant 8 bits represent the unsigned base 256 exponent
// 	* bit 23 (the 24th bit) represents the sign bit
//	* the least significant 23 bits represent the mantissa
//
//	-------------------------------------------------
//	|   Exponent     |    Sign    |    Mantissa     |
//	-------------------------------------------------
//	| 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] |
//	-------------------------------------------------
//
// The formula to calculate N is:
// 	N = (-1^sign) * mantissa * 256^(exponent-3)
//
// This compact form is only used in bitcoin to encode unsigned 256-bit numbers
// which represent difficulty targets, thus there really is not a need for a
// sign bit, but it is implemented here to stay consistent with bitcoind.
func CompactToBig(compact uint32) *big.Int {
	// Extract the mantissa, sign bit, and exponent.
	mantissa := compact & 0x007fffff
	isNegative := compact&0x00800000 != 0
	exponent := uint(compact >> 24)

	// Since the base for the exponent is 256, the exponent can be treated
	// as the number of bytes to represent the full 256-bit number.  So,
	// treat the exponent as the number of bytes and shift the mantissa
	// right or left accordingly.  This is equivalent to:
	// N = mantissa * 256^(exponent-3)
	var bn *big.Int
	if exponent <= 3 {
		mantissa >>= 8 * (3 - exponent)
		bn = big.NewInt(int64(mantissa))
	} else {
		bn = big.NewInt(int64(mantissa))
		bn.Lsh(bn, 8*(exponent-3))
	}

	// Make it negative if the sign bit is set.
	if isNegative {
		bn = bn.Neg(bn)
	}

	return bn
}
Esempio n. 24
0
// ReadCertificate reads a transaction certificate from the TCA.
//
func (tcap *TCAP) ReadCertificate(ctx context.Context, req *pb.TCertReadReq) (*pb.Cert, error) {
	Trace.Println("grpc TCAP:ReadCertificate")

	id := req.Id.Id
	raw, err := tcap.tca.eca.readCertificate(id, x509.KeyUsageDigitalSignature)
	if err != nil {
		return nil, err
	}
	cert, err := x509.ParseCertificate(raw)
	if err != nil {
		return nil, err
	}

	sig := req.Sig
	req.Sig = nil

	r, s := big.NewInt(0), big.NewInt(0)
	r.UnmarshalText(sig.R)
	s.UnmarshalText(sig.S)

	hash := sha3.New384()
	raw, _ = proto.Marshal(req)
	hash.Write(raw)
	if ecdsa.Verify(cert.PublicKey.(*ecdsa.PublicKey), hash.Sum(nil), r, s) == false {
		return nil, errors.New("signature does not verify")
	}

	raw, err = tcap.tca.readCertificate1(id, req.Ts.Seconds)
	if err != nil {
		return nil, err
	}

	return &pb.Cert{raw}, nil
}
Esempio n. 25
0
func TestCRLCreation(t *testing.T) {
	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
	block, _ = pem.Decode([]byte(pemCertificate))
	cert, _ := ParseCertificate(block.Bytes)

	now := time.Unix(1000, 0)
	expiry := time.Unix(10000, 0)

	revokedCerts := []pkix.RevokedCertificate{
		{
			SerialNumber:   big.NewInt(1),
			RevocationTime: now,
		},
		{
			SerialNumber:   big.NewInt(42),
			RevocationTime: now,
		},
	}

	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
	if err != nil {
		t.Errorf("error creating CRL: %s", err)
	}

	_, err = ParseDERCRL(crlBytes)
	if err != nil {
		t.Errorf("error reparsing CRL: %s", err)
	}
}
Esempio n. 26
0
// GenerateSerialNumber generates a serial number suitable for a certificate
func GenerateSerialNumber() (*big.Int, error) {
	serial, err := rand.Int(rand.Reader, (&big.Int{}).Exp(big.NewInt(2), big.NewInt(159), nil))
	if err != nil {
		return nil, InternalError{Err: fmt.Sprintf("error generating serial number: %v", err)}
	}
	return serial, nil
}
func main() {

	//1) calculate 2^1000

	two := big.NewInt(2)
	num := big.NewInt(2)

	for i := 1; i < POWER; i++ { //init at 1 because num is already 2.
		num.Mul(num, two)
	}

	//2) add the digits together.

	str := num.String()
	sum := 0

	for i := 0; i < len(str); i++ {

		sumStr, _ := strconv.Atoi(str[i : i+1])

		sum += sumStr

	}

	fmt.Printf("Power Digit Sum: %v\n", sum)

}
func findMissingElement(first []int64, second []int64) int {
	sum := big.NewInt(0)
	firstLength := len(first)
	lastIndex := firstLength - 1
	secondArrayMap := make(map[int64]int, firstLength)

	for i, secondVal := range second {
		firstVal := first[i]
		diff := int64(firstVal - secondVal)

		// index the 'first array' value
		secondArrayMap[firstVal] = i

		sum = sum.Add(sum, big.NewInt(diff))
		//fmt.Printf("%v| diff = %v - %v = %v, sum = %v\n", i, firstVal, secondVal, diff, sum)
	}

	// add the last value from first array
	lastVal := int64(first[lastIndex])
	// index the last value of the 'first array'
	secondArrayMap[lastVal] = lastIndex

	// finalise sum calculation
	sum = sum.Add(sum, big.NewInt(lastVal))
	// fmt.Printf("add last value from first array = %v\n", lastVal)

	// fmt.Printf("Final sum = %v\n", sum)
	//fmt.Printf("secondArrayMap = %v\n", secondArrayMap)

	return secondArrayMap[sum.Int64()]
}
Esempio n. 29
0
func TestNAF(t *testing.T) {
	negOne := big.NewInt(-1)
	one := big.NewInt(1)
	two := big.NewInt(2)
	for i := 0; i < 1024; i++ {
		data := make([]byte, 32)
		_, err := rand.Read(data)
		if err != nil {
			t.Fatalf("failed to read random data at %d", i)
			break
		}
		nafPos, nafNeg := btcec.NAF(data)
		want := new(big.Int).SetBytes(data)
		got := big.NewInt(0)
		// Check that the NAF representation comes up with the right number
		for i := 0; i < len(nafPos); i++ {
			bytePos := nafPos[i]
			byteNeg := nafNeg[i]
			for j := 7; j >= 0; j-- {
				got.Mul(got, two)
				if bytePos&0x80 == 0x80 {
					got.Add(got, one)
				} else if byteNeg&0x80 == 0x80 {
					got.Add(got, negOne)
				}
				bytePos <<= 1
				byteNeg <<= 1
			}
		}
		if got.Cmp(want) != 0 {
			t.Errorf("%d: Failed NAF got %X want %X", i, got, want)
		}
	}
}
Esempio n. 30
0
func Test_akeHasFinished_wipesAKEKeys(t *testing.T) {
	c := &Conversation{}
	c.ourCurrentKey = bobPrivateKey
	c.theirKey = bobPrivateKey.PublicKey()

	revKey := akeKeys{
		c:  fixedSize(16, []byte{1, 2, 3}),
		m1: fixedSize(32, []byte{4, 5, 6}),
		m2: fixedSize(32, []byte{7, 8, 9}),
	}

	sigKey := akeKeys{
		c:  fixedSize(16, []byte{3, 2, 1}),
		m1: fixedSize(32, []byte{6, 5, 4}),
		m2: fixedSize(32, []byte{9, 8, 7}),
	}

	c.ake = &ake{
		secretExponent:   big.NewInt(1),
		ourPublicValue:   big.NewInt(2),
		theirPublicValue: big.NewInt(2),
		revealKey:        revKey,
		sigKey:           sigKey,
		r:                [16]byte{1, 2, 3},
		encryptedGx:      []byte{1, 2, 3},
		xhashedGx:        fixedSize(otrV3{}.hash2Length(), []byte{1, 2, 3}),
		state:            authStateNone{},
	}

	c.akeHasFinished()

	assertDeepEquals(t, *c.ake, ake{state: c.ake.state})
}