Exemplo n.º 1
0
func encodeBase58Check(val []byte) []byte {
	const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

	// payload
	p := make([]byte, 1+len(val)) // version byte (0x00) + val
	copy(p[1:], val)
	h1 := sha256.Sum256(p)
	h2 := sha256.Sum256(h1[:])

	// value as []byte
	v := make([]byte, len(p)+4) // payload + first 4 bytes of h2
	copy(v, p)
	copy(v[len(p):], h2[:4])

	var res []byte
	x := new(big.Int).SetBytes(v)
	y := big.NewInt(58)
	m, zero := new(big.Int), new(big.Int)

	// convert to base58
	for x.Cmp(zero) > 0 {
		x, m = x.DivMod(x, y, m)
		res = append(res, alphabet[m.Int64()])
	}
	// append '1' for each leading zero byte in value
	for i := 0; v[i] == 0; i++ {
		res = append(res, alphabet[0])
	}
	// reverse
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}

	return res
}
Exemplo n.º 2
0
func EncodeBase58(ba []byte) []byte {
	if len(ba) == 0 {
		return nil
	}

	// Expected size increase from base58 conversion is approximately 137%, use 138% to be safe
	ri := len(ba) * 138 / 100
	ra := make([]byte, ri+1)

	x := new(big.Int).SetBytes(ba) // ba is big-endian
	x.Abs(x)
	y := big.NewInt(58)
	m := new(big.Int)

	for x.Sign() > 0 {
		x, m = x.DivMod(x, y, m)
		ra[ri] = base58[int32(m.Int64())]
		ri--
	}

	// Leading zeroes encoded as base58 zeros
	for i := 0; i < len(ba); i++ {
		if ba[i] != 0 {
			break
		}
		ra[ri] = '1'
		ri--
	}
	return ra[ri+1:]
}
Exemplo n.º 3
0
// Base58Encode encodes a byte slice to a modified base58 string.
func Base58Encode(b []byte, alphabet string) string {
	x := new(big.Int)
	x.SetBytes(b)

	answer := make([]byte, 0)
	for x.Cmp(bigZero) > 0 {
		mod := new(big.Int)
		x.DivMod(x, bigRadix, mod)
		answer = append(answer, alphabet[mod.Int64()])
	}

	// leading zero bytes
	for _, i := range b {
		if i != 0 {
			break
		}
		answer = append(answer, alphabet[0])
	}

	// reverse
	alen := len(answer)
	for i := 0; i < alen/2; i++ {
		answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
	}

	return string(answer)
}
Exemplo n.º 4
0
//Verify verifies the proof file server send.
func (sw *Swizzle) Verify(p Proof) (bool, error) {
	proof, ok := p.(*SwizzleProof)
	if !ok {
		return false, errors.New("use SwizzleProof instance for proof")
	}
	var rhs big.Int
	var dummy big.Int
	ch := sw.lastChallenge
	for i := 0; i < sw.chunks; i++ {
		f, err := keyedPRFBig(sw.fKey, sw.prime, i)
		if err != nil {
			return false, err
		}
		v, err := keyedPRFBig(ch.Key, ch.Vmax, i)
		if err != nil {
			return false, err
		}
		rhs.Add(&rhs, dummy.Mul(v, f))
	}
	for j := 0; j < ch.Sectors; j++ {
		alpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)
		if err != nil {
			return false, err
		}
		rhs.Add(&rhs, dummy.Mul(alpha, &proof.Mu[j]))
	}
	dummy.DivMod(&rhs, sw.prime, &rhs)
	if proof.Sigma.Cmp(&rhs) == 0 {
		return true, nil
	}
	return false, nil
}
Exemplo n.º 5
0
// BigComma produces a string form of the given big.Int in base 10
// with commas after every three orders of magnitude.
func BigComma(b *big.Int) string {
	sign := ""
	if b.Sign() < 0 {
		sign = "-"
		b.Abs(b)
	}

	athousand := big.NewInt(1000)
	c := (&big.Int{}).Set(b)
	_, m := oom(c, athousand)
	parts := make([]string, m+1)
	j := len(parts) - 1

	mod := &big.Int{}
	for b.Cmp(athousand) >= 0 {
		b.DivMod(b, athousand, mod)
		parts[j] = strconv.FormatInt(mod.Int64(), 10)
		switch len(parts[j]) {
		case 2:
			parts[j] = "0" + parts[j]
		case 1:
			parts[j] = "00" + parts[j]
		}
		j--
	}
	parts[j] = strconv.Itoa(int(b.Int64()))
	return sign + strings.Join(parts[j:len(parts)], ",")
}
Exemplo n.º 6
0
// EncodeBigInt returns the base62 encoding of an arbitrary precision integer
func (e *Encoding) EncodeBigInt(n *big.Int) string {
	var (
		b    = make([]byte, 0)
		rem  = new(big.Int)
		bse  = new(big.Int)
		zero = new(big.Int)
	)
	bse.SetInt64(base)
	zero.SetInt64(0)

	// Progressively divide by base, until we hit zero
	// store remainder each time
	// Prepend as an additional character is the higher power
	for n.Cmp(zero) == 1 {
		n, rem = n.DivMod(n, bse, rem)
		b = append([]byte{e.encode[rem.Int64()]}, b...)
	}

	s := string(b)
	if e.padding > 0 {
		s = e.pad(s, e.padding)
	}

	return s
}
Exemplo n.º 7
0
func Sub11(xx *big.Int) big.Int {
	mm := new(big.Int)
	kk := big.NewInt(10)
	yy := new(big.Int)
	yy.DivMod(xx, kk, mm)
	yy.Sub(yy, mm)
	return *yy
}
Exemplo n.º 8
0
// Returns a new big.Int set to the ceiling of x.
func ratCeil(x *big.Rat) *big.Int {
	z := new(big.Int)
	m := new(big.Int)
	z.DivMod(x.Num(), x.Denom(), m)
	if m.Cmp(intZero) == 1 {
		z.Add(z, intOne)
	}
	return z
}
Exemplo n.º 9
0
// total order of magnitude
// (same as above, but with no upper limit)
func oom(n, b *big.Int) (float64, int) {
	mag := 0
	m := &big.Int{}
	for n.Cmp(b) >= 0 {
		n.DivMod(n, b, m)
		mag++
	}
	return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
}
func SumBig(n *big.Int, base int) (sum int) {
	i := new(big.Int).Set(n)
	b := new(big.Int).SetUint64(uint64(base))
	r := new(big.Int)
	for i.BitLen() > 0 {
		i.DivMod(i, b, r)
		sum += int(r.Uint64())
	}
	return
}
Exemplo n.º 11
0
Arquivo: basen.go Projeto: cmars/oo
// EncodeToString returns the base-encoded string representation
// of the given bytes.
func (enc *Encoding) EncodeToString(b []byte) string {
	n := new(big.Int)
	r := new(big.Int)
	n.SetBytes(b)
	var result []byte
	for n.Cmp(zero) > 0 {
		n, r = n.DivMod(n, enc.base, r)
		result = append([]byte{enc.alphabet[r.Int64()]}, result...)
	}
	return string(result)
}
Exemplo n.º 12
0
// order of magnitude (to a max order)
func oomm(n, b *big.Int, maxmag int) (float64, int) {
	mag := 0
	m := &big.Int{}
	for n.Cmp(b) >= 0 {
		n.DivMod(n, b, m)
		mag++
		if mag == maxmag && maxmag >= 0 {
			break
		}
	}
	return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
}
Exemplo n.º 13
0
// TODO: Pass in result, so it can be reused.
func reverse(n *big.Int) (result *big.Int) {
	result = big.NewInt(0)
	var work big.Int
	work.Set(n)
	tmp := big.NewInt(0)

	for work.Cmp(zero) != 0 {
		work.DivMod(&work, ten, tmp)
		result.Mul(result, ten)
		result.Add(result, tmp)
	}
	return
}
Exemplo n.º 14
0
func NumberEncode(number string, alphabet []byte) string {
	token := make([]byte, 0, 12)
	x, ok := new(big.Int).SetString(number, 10)
	if !ok {
		return ""
	}
	y := big.NewInt(int64(len(alphabet)))
	m := new(big.Int)
	for x.Sign() > 0 {
		x, m = x.DivMod(x, y, m)
		token = append(token, alphabet[int(m.Int64())])
	}
	return string(token)
}
Exemplo n.º 15
0
func EncodeAlphabet(alphabet, bs []byte) string {
	base := big.NewInt(int64(len(alphabet)))
	result := make([]byte, 0)

	num := new(big.Int).SetBytes(bs)
	rem := new(big.Int)

	for num.Sign() != 0 {
		num.DivMod(num, base, rem)

		result = append(result, alphabet[rem.Int64()])
	}

	return string(result)
}
Exemplo n.º 16
0
func digitSum(num *big.Int) (sum int) {
	zero := big.NewInt(0)
	ten := big.NewInt(10)

	var work big.Int
	work.Set(num)

	tmp := big.NewInt(0)

	for work.Cmp(zero) > 0 {
		work.DivMod(&work, ten, tmp)
		sum += int(tmp.Int64())
	}
	return
}
Exemplo n.º 17
0
func sumDigitsFac(num int64) int64 {
	n := new(big.Int)
	n.MulRange(1, num)

	ten := big.NewInt(10)
	d := new(big.Int)
	var sum int64

	for n.BitLen() > 0 {
		n.DivMod(n, ten, d)
		sum += d.Int64()
	}

	return sum
}
Exemplo n.º 18
0
func digitCount(n *big.Int) int {
	zero := big.NewInt(0)
	ten := big.NewInt(10)
	var work big.Int
	work.Set(n)
	tmp := big.NewInt(0)

	count := 0

	for work.Cmp(zero) > 0 {
		work.DivMod(&work, ten, tmp)
		count += 1
	}

	return count
}
Exemplo n.º 19
0
//Prove make the proof from the file and SwizzleChallenge which is send by a client.
func (ch *SwizzleChallenge) Prove(file io.ReadSeeker, tag Tag) (Proof, error) {
	var dummy big.Int

	swtag, ok := tag.(*SwizzleTag)
	if !ok {
		return nil, errors.New("use SwizzleTag instance for tag")
	}

	sectorSize := (ch.Vmax.BitLen() + 7) >> 3
	proof := &SwizzleProof{}
	proof.Mu = make([]big.Int, ch.Sectors)
	proof.Sigma = new(big.Int)

	buffer := make([]byte, sectorSize)
	var mij big.Int
	for i := 0; i < ch.Chunks; i++ {
		v, err := keyedPRFBig(ch.Key, ch.Vmax, i)
		if err != nil {
			return nil, err
		}
		for j := 0; j < ch.Sectors; j++ {
			n, err := file.Read(buffer)
			if err != nil {
				return nil, err
			}
			if n > 0 {
				mij.SetBytes(buffer)
				proof.Mu[j].Add(&proof.Mu[j], dummy.Mul(v, &mij))
			}
			if n != sectorSize {
				break
			}
		}
		defer func() {
			if e := recover(); e != nil {
				logging.Println(len(swtag.Sigmas))
				logging.Println(i)
			}
		}()
		proof.Sigma.Add(proof.Sigma, dummy.Mul(v, swtag.Sigmas[i]))
	}
	for j := 0; j < ch.Sectors; j++ {
		dummy.DivMod(&proof.Mu[j], ch.Vmax, &proof.Mu[j])
	}
	dummy.DivMod(proof.Sigma, ch.Vmax, proof.Sigma)
	return proof, nil
}
Exemplo n.º 20
0
// Encode encodes src, appending to dst. Be sure to use the returned
// new value of dst.
func (self *encodingAlphabet) EncodeBig(dst []byte, src *big.Int) []byte {
	start := len(dst)
	n := new(big.Int)
	n.Set(src)
	radix := big.NewInt(58)
	zero := big.NewInt(0)

	for n.Cmp(zero) > 0 {
		mod := new(big.Int)
		n.DivMod(n, radix, mod)
		dst = append(dst, self.alphabet[mod.Int64()])
	}

	for i, j := start, len(dst)-1; i < j; i, j = i+1, j-1 {
		dst[i], dst[j] = dst[j], dst[i]
	}
	return dst
}
Exemplo n.º 21
0
func sumDigitsPow(base, exp int64) int64 {
	b := big.NewInt(base)
	e := big.NewInt(exp)
	n := new(big.Int)

	n.Exp(b, e, nil)

	ten := big.NewInt(10)
	d := new(big.Int)
	var sum int64

	for n.BitLen() > 0 {
		n.DivMod(n, ten, d)
		sum += d.Int64()
	}

	return sum
}
Exemplo n.º 22
0
// Encode encodes src, appending to dst. Be sure to use the returned
// new value of dst.
func Base36Encode(dst []byte, src *big.Int) []byte {
	start := len(dst)
	n := new(big.Int)
	n.Set(src)
	radix := big.NewInt(alphabetSize)
	zero := big.NewInt(0)

	for n.Cmp(zero) > 0 {
		mod := new(big.Int)
		n.DivMod(n, radix, mod)
		dst = append(dst, alphabet[mod.Int64()])
	}

	for i, j := start, len(dst)-1; i < j; i, j = i+1, j-1 {
		dst[i], dst[j] = dst[j], dst[i]
	}
	return dst
}
Exemplo n.º 23
0
func ConvertTo62(raw []byte) string {
	bi := big.Int{}
	bi.SetBytes(raw)
	rem := big.NewInt(0)
	base := big.NewInt(62)
	zero := big.NewInt(0)
	result := ""

	for bi.Cmp(zero) > 0 {
		_, rem = bi.DivMod(&bi, base, rem)
		result += string(alphabet[int(rem.Uint64())])
	}

	for len(result) < 22 {
		result += "0"
	}
	return reverse(result)
}
Exemplo n.º 24
0
//Encode makes a sigmas which iis sent to server.
func (sw *Swizzle) Encode(file io.ReadSeeker, n int) (Tag, error) {
	var dummy big.Int

	tag := SwizzleTag{}
	tag.Sigmas = make([]*big.Int, 0)

	sectorSize := (sw.prime.BitLen() + 7) >> 3
	chunkID := 0
	buffer := make([]byte, sectorSize)
	var mij big.Int
	alphas := make([]*big.Int, sw.sectors)
	for j := 0; j < sw.sectors; j++ {
		alpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)
		if err != nil {
			return nil, err
		}
		alphas[j] = alpha
	}
	for done := false; !done; chunkID++ {
		sigma, err := keyedPRFBig(sw.fKey, sw.prime, chunkID)
		if err != nil {
			return nil, err
		}

		for j := 0; j < sw.sectors; j++ {
			n, err := file.Read(buffer)
			if err != nil {
				return nil, err
			}
			if n > 0 {
				mij.SetBytes(buffer)
				sigma.Add(sigma, dummy.Mul(alphas[j], &mij))
			}
			if n != sectorSize {
				done = true
				break
			}
		}
		dummy.DivMod(sigma, sw.prime, sigma)
		tag.Sigmas = append(tag.Sigmas, sigma)
	}
	sw.chunks = chunkID
	return &tag, nil
}
Exemplo n.º 25
0
// EncodeBigToBase58 encodes src, appending to dst. Be sure to use the returned
// new value of dst.
func EncodeBigToBase58(dst []byte, src *big.Int) []byte {
	start := len(dst)
	n := new(big.Int)
	n.Set(src)
	radix := big.NewInt(58)
	zero := big.NewInt(0)

	for n.Cmp(zero) > 0 {
		mod := new(big.Int)
		n.DivMod(n, radix, mod)
		dst = append(dst, alphabet[mod.Int64()])
	}

	// reverse string
	for i, j := start, len(dst)-1; i < j; i, j = i+1, j-1 {
		dst[i], dst[j] = dst[j], dst[i]
	}
	return dst
}
Exemplo n.º 26
0
func (e *Encoding) enc(dst []byte, x *big.Int, src []byte) []byte {
	if dst == nil {
		dst = make([]byte, EncodedLen(x.BitLen()))
	}
	i := len(dst)
	for x.Cmp(zero) > 0 {
		i--
		mod := new(big.Int)
		x.DivMod(x, radix, mod)
		dst[i] = e.encode[mod.Uint64()]
	}
	if e.padChar != NoPadding {
		for src[i] == 0x00 {
			i--
			dst[i] = byte(e.padChar)
		}
	}
	return dst[i:]
}
Exemplo n.º 27
0
Arquivo: id.go Projeto: etcenter/c4
// Bytes encodes the written bytes to C4 ID format.
func (id *ID) Bytes() []byte {
	var bigNum big.Int
	bigID := big.Int(*id)
	bigNum.Set(&bigID)
	bigBase := big.NewInt(base)
	bigZero := big.NewInt(0)
	bigMod := new(big.Int)
	var encoded []byte
	for bigNum.Cmp(bigZero) > 0 {
		bigNum.DivMod(&bigNum, bigBase, bigMod)
		encoded = append([]byte{charset[bigMod.Int64()]}, encoded...)
	}
	// padding
	diff := idlen - 2 - len(encoded)
	encoded = append(bytes.Repeat(lowbyte, diff), encoded...)
	// c4... prefix
	encoded = append(prefix, encoded...)
	return encoded
}
Exemplo n.º 28
0
func Encodeb58(a []byte) (s string) {
	idx := len(a)*138/100 + 1
	buf := make([]byte, idx)
	bn := new(big.Int).SetBytes(a)
	var mo *big.Int
	for bn.Cmp(bn0) != 0 {
		bn, mo = bn.DivMod(bn, bn58, new(big.Int))
		idx--
		buf[idx] = b58set[mo.Int64()]
	}
	for i := range a {
		if a[i] != 0 {
			break
		}
		idx--
		buf[idx] = b58set[0]
	}

	s = string(buf[idx:])

	return
}
Exemplo n.º 29
0
func Trial(n *big.Int) (primes []*big.Int, composites []*big.Int) {

	var z big.Int
	var m big.Int

	bigp := big.NewInt(0)

	for _, p := range smallPrimes {
		for {
			// reuse the existing bigint
			bigp.SetInt64(p)
			z.DivMod(n, bigp, &m)
			if m.Sign() != 0 {
				break
			}
			n.Set(&z)
			primes = append(primes, bigp)
			// create a new bigint, since we just stored the one we were using
			bigp = big.NewInt(0)
		}

		if n.Cmp(one) == 0 {
			break
		}
	}

	if n.Cmp(one) > 0 {
		if n.ProbablyPrime(10) {
			primes = append(primes, n)
		} else {
			composites = append(composites, n)
		}
	}

	return primes, composites
}
Exemplo n.º 30
0
func TestTruncateRound(t *testing.T) {
	var (
		bsec  = new(big.Int)
		bnsec = new(big.Int)
		bd    = new(big.Int)
		bt    = new(big.Int)
		br    = new(big.Int)
		bq    = new(big.Int)
		b1e9  = new(big.Int)
	)

	b1e9.SetInt64(1e9)

	testOne := func(ti, tns, di int64) bool {
		t0 := Unix(ti, int64(tns)).UTC()
		d := Duration(di)
		if d < 0 {
			d = -d
		}
		if d <= 0 {
			d = 1
		}

		// Compute bt = absolute nanoseconds.
		sec, nsec := abs(t0)
		bsec.SetInt64(sec)
		bnsec.SetInt64(nsec)
		bt.Mul(bsec, b1e9)
		bt.Add(bt, bnsec)

		// Compute quotient and remainder mod d.
		bd.SetInt64(int64(d))
		bq.DivMod(bt, bd, br)

		// To truncate, subtract remainder.
		// br is < d, so it fits in an int64.
		r := br.Int64()
		t1 := t0.Add(-Duration(r))

		// Check that time.Truncate works.
		if trunc := t0.Truncate(d); trunc != t1 {
			t.Errorf("Time.Truncate(%s, %s) = %s, want %s\n"+
				"%v trunc %v =\n%v want\n%v",
				t0.Format(RFC3339Nano), d, trunc, t1.Format(RFC3339Nano),
				absString(t0), int64(d), absString(trunc), absString(t1))
			return false
		}

		// To round, add d back if remainder r > d/2 or r == exactly d/2.
		// The commented out code would round half to even instead of up,
		// but that makes it time-zone dependent, which is a bit strange.
		if r > int64(d)/2 || r+r == int64(d) /*&& bq.Bit(0) == 1*/ {
			t1 = t1.Add(Duration(d))
		}

		// Check that time.Round works.
		if rnd := t0.Round(d); rnd != t1 {
			t.Errorf("Time.Round(%s, %s) = %s, want %s\n"+
				"%v round %v =\n%v want\n%v",
				t0.Format(RFC3339Nano), d, rnd, t1.Format(RFC3339Nano),
				absString(t0), int64(d), absString(rnd), absString(t1))
			return false
		}
		return true
	}

	// manual test cases
	for _, tt := range truncateRoundTests {
		testOne(tt.t.Unix(), int64(tt.t.Nanosecond()), int64(tt.d))
	}

	// exhaustive near 0
	for i := 0; i < 100; i++ {
		for j := 1; j < 100; j++ {
			testOne(unixToZero, int64(i), int64(j))
			testOne(unixToZero, -int64(i), int64(j))
			if t.Failed() {
				return
			}
		}
	}

	if t.Failed() {
		return
	}

	// randomly generated test cases
	cfg := &quick.Config{MaxCount: 100000}
	if testing.Short() {
		cfg.MaxCount = 1000
	}

	// divisors of Second
	f1 := func(ti int64, tns int32, logdi int32) bool {
		d := Duration(1)
		a, b := uint(logdi%9), (logdi>>16)%9
		d <<= a
		for i := 0; i < int(b); i++ {
			d *= 5
		}
		return testOne(ti, int64(tns), int64(d))
	}
	quick.Check(f1, cfg)

	// multiples of Second
	f2 := func(ti int64, tns int32, di int32) bool {
		d := Duration(di) * Second
		if d < 0 {
			d = -d
		}
		return testOne(ti, int64(tns), int64(d))
	}
	quick.Check(f2, cfg)

	// halfway cases
	f3 := func(tns, di int64) bool {
		di &= 0xfffffffe
		if di == 0 {
			di = 2
		}
		tns -= tns % di
		if tns < 0 {
			tns += di / 2
		} else {
			tns -= di / 2
		}
		return testOne(0, tns, di)
	}
	quick.Check(f3, cfg)

	// full generality
	f4 := func(ti int64, tns int32, di int64) bool {
		return testOne(ti, int64(tns), di)
	}
	quick.Check(f4, cfg)
}