Exemplo n.º 1
1
func TestTeeReader(t *testing.T) {
	src := []byte("hello, world")
	dst := make([]byte, len(src))
	rb := bytes.NewBuffer(src)
	wb := new(bytes.Buffer)
	r := TeeReader(rb, wb)
	if n, err := ReadFull(r, dst); err != nil || n != len(src) {
		t.Fatalf("ReadFull(r, dst) = %d, %v; want %d, nil", n, err, len(src))
	}
	if !bytes.Equal(dst, src) {
		t.Errorf("bytes read = %q want %q", dst, src)
	}
	if !bytes.Equal(wb.Bytes(), src) {
		t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
	}
	if n, err := r.Read(dst); n != 0 || err != EOF {
		t.Errorf("r.Read at EOF = %d, %v want 0, EOF", n, err)
	}
	rb = bytes.NewBuffer(src)
	pr, pw := Pipe()
	pr.Close()
	r = TeeReader(rb, pw)
	if n, err := ReadFull(r, dst); n != 0 || err != ErrClosedPipe {
		t.Errorf("closed tee: ReadFull(r, dst) = %d, %v; want 0, EPIPE", n, err)
	}
}
Exemplo n.º 2
1
func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *types.PrivValidator, votedBlockHash, lockedBlockHash []byte) {
	precommits := cs.Votes.Precommits(thisRound)
	var vote *types.Vote
	if vote = precommits.GetByAddress(privVal.Address); vote == nil {
		panic("Failed to find precommit from validator")
	}

	if votedBlockHash == nil {
		if vote.BlockHash != nil {
			panic("Expected precommit to be for nil")
		}
	} else {
		if !bytes.Equal(vote.BlockHash, votedBlockHash) {
			panic("Expected precommit to be for proposal block")
		}
	}

	if lockedBlockHash == nil {
		if cs.LockedRound != lockRound || cs.LockedBlock != nil {
			panic(fmt.Sprintf("Expected to be locked on nil at round %d. Got locked at round %d with block %v", lockRound, cs.LockedRound, cs.LockedBlock))
		}
	} else {
		if cs.LockedRound != lockRound || !bytes.Equal(cs.LockedBlock.Hash(), lockedBlockHash) {
			panic(fmt.Sprintf("Expected block to be locked on round %d, got %d. Got locked block %X, expected %X", lockRound, cs.LockedRound, cs.LockedBlock.Hash(), lockedBlockHash))
		}
	}

}
func TestMain2(t *testing.T) {

	fail := false
	for i := 0; i < 6*1024; i++ {

		seed := RandByte(32)
		//seed2 := RandByte(32)

		pubkey1, seckey1 := _GenerateDeterministicKeyPair(seed)
		pubkey2, seckey2 := GenerateDeterministicKeyPair(seed)

		if bytes.Equal(seckey1, seckey2) == false {
			fail = true
			log.Printf("deterministic seckeys do not match %d", i)
		}
		if bytes.Equal(pubkey1, pubkey2) == false {
			fail = true
			log.Printf("deterministic pubkeys do not match %d", i)
		}
	}

	if fail == true {
		log.Fatal("Failed")
	}
}
Exemplo n.º 4
1
func TestMarshaling(t *testing.T) {

	test := func(d1 []byte, rid1 RequestID) {
		d2, err := wrapData(d1, rid1)
		if err != nil {
			t.Error(err)
		}

		d3, rid2, err := unwrapData(d2)
		if err != nil {
			t.Error(err)
		}

		d4, err := wrapData(d3, rid1)
		if err != nil {
			t.Error(err)
		}

		if !bytes.Equal(rid2, rid1) {
			t.Error("RequestID fail")
		}

		if !bytes.Equal(d1, d3) {
			t.Error("unmarshalled data should be the same")
		}

		if !bytes.Equal(d2, d4) {
			t.Error("marshalled data should be the same")
		}
	}

	test([]byte("foo"), []byte{1, 2, 3, 4})
	test([]byte("bar"), nil)
}
Exemplo n.º 5
1
func TestMakeKey(t *testing.T) {
	if !bytes.Equal(makeKey(roachpb.Key("A"), roachpb.Key("B")), roachpb.Key("AB")) ||
		!bytes.Equal(makeKey(roachpb.Key("A")), roachpb.Key("A")) ||
		!bytes.Equal(makeKey(roachpb.Key("A"), roachpb.Key("B"), roachpb.Key("C")), roachpb.Key("ABC")) {
		t.Fatalf("MakeKey is broken")
	}
}
Exemplo n.º 6
0
func TestLineTooLong(t *testing.T) {
	data := make([]byte, 0)
	for i := 0; i < minReadBufferSize*5/2; i++ {
		data = append(data, '0'+byte(i%10))
	}
	buf := bytes.NewBuffer(data)
	l := bufio.NewReaderSize(buf, minReadBufferSize)
	line, isPrefix, err := l.ReadLine()
	if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
		t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
	}
	data = data[len(line):]
	line, isPrefix, err = l.ReadLine()
	if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
		t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
	}
	data = data[len(line):]
	line, isPrefix, err = l.ReadLine()
	if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
		t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
	}
	line, isPrefix, err = l.ReadLine()
	if isPrefix || err == nil {
		t.Errorf("expected no more lines: %x %s", line, err)
	}
}
Exemplo n.º 7
0
// Test that sealing a message and then opening it works and returns
// the original message.
func TestSealOpen(t *testing.T) {
	kp1, kp2 := makeKeyPairsOrBust(t)

	expectedData := []byte{0, 1, 2, 3, 4}
	nonce := [24]byte{5, 6, 7, 8}

	encryptedData := boxSeal(expectedData, nonce, kp1.Public, kp2.Private)

	data, err := boxOpen(encryptedData, nonce, kp2.Public, kp1.Private)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(data, expectedData) {
		t.Errorf("Expected %v, got %v", expectedData, data)
	}

	// Apparently, you can open a message you yourself have sealed.

	data, err = boxOpen(encryptedData, nonce, kp1.Public, kp2.Private)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(data, expectedData) {
		t.Errorf("Expected %v, got %v", expectedData, data)
	}
}
Exemplo n.º 8
0
// Trying to add packet to existing message or creating new message
//
// For TCP message unique id is Acknowledgment number (see tcp_packet.go)
func (t *Listener) processTCPPacket(packet *TCPPacket) {
	defer func() { recover() }()

	var message *TCPMessage

	if parentAck, ok := t.seqWithData[packet.Seq]; ok {
		t.ackAliases[packet.Ack] = parentAck
		delete(t.seqWithData, packet.Seq)
	}

	if alias, ok := t.ackAliases[packet.Ack]; ok {
		packet.Ack = alias
	}

	mID := packet.Addr.String() + strconv.Itoa(int(packet.SrcPort)) + strconv.Itoa(int(packet.Ack))
	message, ok := t.messages[mID]

	if !ok {
		// We sending messageDelChan channel, so message object can communicate with Listener and notify it if message completed
		message = NewTCPMessage(mID, t.messageDelChan, packet.Ack)
		t.messages[mID] = message
	}

	if bytes.Equal(packet.Data[0:4], bPOST) {
		if bytes.Equal(packet.Data[len(packet.Data)-24:len(packet.Data)-4], bExpect100ContinueCheck) {
			t.seqWithData[packet.Seq+uint32(len(packet.Data))] = packet.Ack

			// Removing `Expect: 100-continue` header
			packet.Data = append(packet.Data[:len(packet.Data)-24], packet.Data[len(packet.Data)-2:]...)
		}
	}

	// Adding packet to message
	message.packetsChan <- packet
}
Exemplo n.º 9
0
// Tests on verifying the rebundle flag and error code in Bundle.Status when rebundling.
func TestRebundleFromPEM(t *testing.T) {
	newBundler := newCustomizedBundlerFromFile(t, testCFSSLRootBundle, interL1, "")
	newBundle, err := newBundler.BundleFromPEMorDER(expiredBundlePEM, nil, Optimal, "")
	if err != nil {
		t.Fatalf("Re-bundle failed. %s", err.Error())
	}
	newChain := newBundle.Chain

	if len(newChain) != 2 {
		t.Fatalf("Expected bundle chain length is 2. Got %d.", len(newChain))
	}

	expiredChain, _ := helpers.ParseCertificatesPEM(expiredBundlePEM)
	for i, cert := range newChain {
		old := expiredChain[i]
		if i == 0 {
			if !bytes.Equal(old.Signature, cert.Signature) {
				t.Fatal("Leaf cert should be the same.")
			}
		} else {
			if bytes.Equal(old.Signature, cert.Signature) {
				t.Fatal("Intermediate cert should be different.")
			}
		}
	}
	// The status must be {Code: ExpiringBit is not set, IsRebundled:true, ExpiringSKIs:{}}
	if len(newBundle.Status.ExpiringSKIs) != 0 || !newBundle.Status.IsRebundled || newBundle.Status.Code&errors.BundleExpiringBit != 0 {
		t.Fatal("Rebundle Status is incorrect.")
	}

}
Exemplo n.º 10
0
func TestParseTag(t *testing.T) {
	for i, tt := range parseTagTests {
		tag, rest, ok := parseTag(tt.in)
		if !tt.ok {
			if ok {
				t.Errorf("%d. parseTag(%v) unexpectedly succeeded.", i, tt.in)
			} else if !bytes.Equal(rest, tt.in) {
				t.Errorf("%d. parseTag(%v) did not preserve input.", i, tt.in)
			}
		} else {
			if !ok {
				t.Errorf("%d. parseTag(%v) unexpectedly failed.", i, tt.in)
			} else if tag != tt.tag || len(rest) != 0 {
				t.Errorf("%d. parseTag(%v) = %v, %v wanted %v, [].", i, tt.in, tag, rest, tt.tag)
			}

			// Test again with trailing data.
			in := make([]byte, len(tt.in)+5)
			copy(in, tt.in)
			tag, rest, ok = parseTag(in)
			if !ok {
				t.Errorf("%d. parseTag(%v) unexpectedly failed.", i, in)
			} else if tag != tt.tag || !bytes.Equal(rest, in[len(tt.in):]) {
				t.Errorf("%d. parseTag(%v) = %v, %v wanted %v, %v.", i, in, tag, rest, tt.tag, in[len(tt.in):])
			}
		}
	}
}
Exemplo n.º 11
0
// TestFilterAddCrossProtocol tests the MsgFilterAdd API when encoding with the
// latest protocol version and decoding with BIP0031Version.
func TestFilterAddCrossProtocol(t *testing.T) {
	data := []byte{0x01, 0x02}
	msg := wire.NewMsgFilterAdd(data)
	if !bytes.Equal(msg.Data, data) {
		t.Errorf("should get same data back out")
	}

	// Encode with latest protocol version.
	var buf bytes.Buffer
	err := msg.BtcEncode(&buf, wire.ProtocolVersion)
	if err != nil {
		t.Errorf("encode of MsgFilterAdd failed %v err <%v>", msg, err)
	}

	// Decode with old protocol version.
	var readmsg wire.MsgFilterAdd
	err = readmsg.BtcDecode(&buf, wire.BIP0031Version)
	if err == nil {
		t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+
			"have %v", msg)
	}

	// Since one of the protocol versions doesn't support the filteradd
	// message, make sure the data didn't get encoded and decoded back out.
	if bytes.Equal(msg.Data, readmsg.Data) {
		t.Error("should not get same data for cross protocol")
	}

}
Exemplo n.º 12
0
// QuoteVerify verifies that a quote was genuinely provided by the TPM. It
// takes the quote data, quote validation blob, public half of the AIK,
// current PCR values and the nonce used in the original quote request. It
// then verifies that the validation block is a valid signature for the
// quote data, that the secrets are the same (in order to avoid replay
// attacks), and that the PCR values are the same. It returns an error if
// any stage of the validation fails.
func QuoteVerify(data []byte, validation []byte, aikpub []byte, pcrvalues [][]byte, secret []byte) error {
	n := big.NewInt(0)
	n.SetBytes(aikpub)
	e := 65537

	pKey := rsa.PublicKey{N: n, E: int(e)}

	dataHash := sha1.Sum(data[:])

	err := rsa.VerifyPKCS1v15(&pKey, crypto.SHA1, dataHash[:], validation)
	if err != nil {
		return err
	}

	pcrHash := data[8:28]
	nonceHash := data[28:48]

	secretHash := sha1.Sum(secret[:])

	if bytes.Equal(secretHash[:], nonceHash) == false {
		return fmt.Errorf("Secret doesn't match")
	}

	pcrComposite := []byte{0x00, 0x02, 0xff, 0xff, 0x00, 0x00, 0x01, 0x40}
	for i := 0; i < 16; i++ {
		pcrComposite = append(pcrComposite, pcrvalues[i]...)
	}
	pcrCompositeHash := sha1.Sum(pcrComposite[:])

	if bytes.Equal(pcrCompositeHash[:], pcrHash) == false {
		return fmt.Errorf("PCR values don't match")
	}

	return nil
}
Exemplo n.º 13
0
func TestMultiReadWrite(t *testing.T) {
	send := []byte("hello world, this message is longer")
	c := make(chan *StreamChunk)
	writer := NewChanWriter(c)
	reader := NewChanReader(c)
	go func() {
		writer.Write(send[:9])
		writer.Write(send[9:19])
		writer.Write(send[19:])
		writer.Close()
	}()
	buf := make([]byte, 10)
	read := 0
	for i := 0; i < len(send)/10; i++ {
		n, err := reader.Read(buf)
		if err != nil {
			t.Fatal("Couldn't read from stream", err)
		}
		if !bytes.Equal(buf[:n], send[read:read+n]) {
			t.Fatal("Got wrong message from stream", string(buf))
		}
		read += n
	}
	n, err := reader.Read(buf)
	if err != io.EOF {
		t.Fatal("Read returned wrong error after close:", err)
	}
	if !bytes.Equal(buf[:n], send[len(send)-n:]) {
		t.Fatal("Got wrong message from stream", string(buf[:n]))
	}
}
Exemplo n.º 14
0
func (p *ProtocolV2) Exec(client *ClientV2, params [][]byte) ([]byte, error) {
	switch {
	case bytes.Equal(params[0], []byte("FIN")):
		return p.FIN(client, params)
	case bytes.Equal(params[0], []byte("RDY")):
		return p.RDY(client, params)
	case bytes.Equal(params[0], []byte("REQ")):
		return p.REQ(client, params)
	case bytes.Equal(params[0], []byte("PUB")):
		return p.PUB(client, params)
	case bytes.Equal(params[0], []byte("MPUB")):
		return p.MPUB(client, params)
	case bytes.Equal(params[0], []byte("NOP")):
		return p.NOP(client, params)
	case bytes.Equal(params[0], []byte("TOUCH")):
		return p.TOUCH(client, params)
	case bytes.Equal(params[0], []byte("IDENTIFY")):
		return p.IDENTIFY(client, params)
	case bytes.Equal(params[0], []byte("SUB")):
		return p.SUB(client, params)
	case bytes.Equal(params[0], []byte("CLS")):
		return p.CLS(client, params)
	}
	return nil, util.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid command %s", params[0]))
}
Exemplo n.º 15
0
func TestSectionTableMerge(t *testing.T) {
	o1 := vm.NewObject()
	o1.SecTab = vm.SectionTable{
		vm.TEXT: []byte{0x1, 0x2},
		vm.DATA: []byte{0xa, 0xb, 0xc},
	}
	o2 := vm.NewObject()
	o2.SecTab = vm.SectionTable{
		vm.TEXT: []byte{0x3, 0x4},
		vm.DATA: []byte{0xd, 0xe, 0xf},
	}

	if err := o1.Merge(o2); err != nil {
		log.Fatal(err)
	}

	text := []byte{0x1, 0x2, 0x3, 0x4}
	data := []byte{0xa, 0xb, 0xc, 0xd, 0xe, 0xf}

	if !bytes.Equal(o1.SecTab[vm.TEXT], text) {
		t.Fatal("expected", text, "got", o1.SecTab[vm.TEXT])
	}
	if !bytes.Equal(o1.SecTab[vm.DATA], data) {
		t.Fatal("expected", data, "got", o1.SecTab[vm.DATA])
	}
}
Exemplo n.º 16
0
// Validate symmetric decryption with Twofish:
//	* ensure the previously encrypted ciphertext can be successfully
//	  decrypted
//	* ensure decryption fails when ciphertext is too short
//	* ensure decryption with invalid Twofish key fails
//	* ensure decryption with the wrong key fails to recover the plaintext
func TestDecrypt(t *testing.T) {
	out, err := decrypt(testKey[:32], testCT)
	if err != nil {
		fmt.Println("secretbox: decrypt failed")
		fmt.Printf("\t%v\n", err)
		t.FailNow()
	} else if !bytes.Equal(out, testMsg) {
		fmt.Println("secretbox: decrypted message doesn't match original")
		t.FailNow()
	}

	_, err = decrypt(testKey[:], testCT[:4])
	if err == nil {
		fmt.Println("secretbox: decryption should fail when ciphertext is too short")
		t.FailNow()
	}

	_, err = decrypt(testKey[:], testCT)
	if err == nil {
		fmt.Println("secretbox: decryption should fail with invalid key")
		t.FailNow()
	}

	var badKey [32]byte
	out, err = decrypt(badKey[:], testCT)
	if err != nil {
		fmt.Println("secretbox: decrypt failed")
		fmt.Printf("\t%v\n", err)
		t.FailNow()
	} else if bytes.Equal(out, testMsg) {
		fmt.Println("secretbox: decrypted message shouldn't match original")
		t.FailNow()
	}
}
Exemplo n.º 17
0
func TestNodeID(t *testing.T) {
	nid := []byte{1, 2, 3, 4, 5, 6}
	SetNodeInterface("")
	s := NodeInterface()
	if s == "" || s == "user" {
		t.Errorf("NodeInterface %q after SetInteface\n", s)
	}
	node1 := NodeID()
	if node1 == nil {
		t.Errorf("NodeID nil after SetNodeInterface\n", s)
	}
	SetNodeID(nid)
	s = NodeInterface()
	if s != "user" {
		t.Errorf("Expected NodeInterface %q got %q\n", "user", s)
	}
	node2 := NodeID()
	if node2 == nil {
		t.Errorf("NodeID nil after SetNodeID\n", s)
	}
	if bytes.Equal(node1, node2) {
		t.Errorf("NodeID not changed after SetNodeID\n", s)
	} else if !bytes.Equal(nid, node2) {
		t.Errorf("NodeID is %x, expected %x\n", node2, nid)
	}
}
Exemplo n.º 18
0
func TestDecryptOAEP(t *testing.T) {
	random := rand.Reader

	sha1 := sha1.New()
	n := new(big.Int)
	d := new(big.Int)
	for i, test := range testEncryptOAEPData {
		n.SetString(test.modulus, 16)
		d.SetString(test.d, 16)
		private := new(PrivateKey)
		private.PublicKey = PublicKey{n, test.e}
		private.D = d

		for j, message := range test.msgs {
			out, err := DecryptOAEP(sha1, nil, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d error: %s", i, j, err)
			} else if !bytes.Equal(out, message.in) {
				t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in)
			}

			// Decrypt with blinding.
			out, err = DecryptOAEP(sha1, random, private, message.out, nil)
			if err != nil {
				t.Errorf("#%d,%d (blind) error: %s", i, j, err)
			} else if !bytes.Equal(out, message.in) {
				t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in)
			}
		}
		if testing.Short() {
			break
		}
	}
}
Exemplo n.º 19
0
func compareBatch(t *testing.T, b1, b2 *Batch) {
	if b1.seq != b2.seq {
		t.Errorf("invalid seq number want %d, got %d", b1.seq, b2.seq)
	}
	if b1.Len() != b2.Len() {
		t.Fatalf("invalid record length want %d, got %d", b1.Len(), b2.Len())
	}
	p1, p2 := new(testBatch), new(testBatch)
	err := b1.Replay(p1)
	if err != nil {
		t.Fatal("error when replaying batch 1: ", err)
	}
	err = b2.Replay(p2)
	if err != nil {
		t.Fatal("error when replaying batch 2: ", err)
	}
	for i := range p1.rec {
		r1, r2 := p1.rec[i], p2.rec[i]
		if r1.kt != r2.kt {
			t.Errorf("invalid type on record '%d' want %d, got %d", i, r1.kt, r2.kt)
		}
		if !bytes.Equal(r1.key, r2.key) {
			t.Errorf("invalid key on record '%d' want %s, got %s", i, string(r1.key), string(r2.key))
		}
		if r1.kt == ktVal {
			if !bytes.Equal(r1.value, r2.value) {
				t.Errorf("invalid value on record '%d' want %s, got %s", i, string(r1.value), string(r2.value))
			}
		}
	}
}
Exemplo n.º 20
0
func TestOFB(t *testing.T) {
	for _, tt := range ofbTests {
		test := tt.name

		c, err := aes.NewCipher(tt.key)
		if err != nil {
			t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
			continue
		}

		for j := 0; j <= 5; j += 5 {
			plaintext := tt.in[0 : len(tt.in)-j]
			ofb := cipher.NewOFB(c, tt.iv)
			ciphertext := make([]byte, len(plaintext))
			ofb.XORKeyStream(ciphertext, plaintext)
			if !bytes.Equal(ciphertext, tt.out[:len(plaintext)]) {
				t.Errorf("%s/%d: encrypting\ninput % x\nhave % x\nwant % x", test, len(plaintext), plaintext, ciphertext, tt.out)
			}
		}

		for j := 0; j <= 5; j += 5 {
			ciphertext := tt.out[0 : len(tt.in)-j]
			ofb := cipher.NewOFB(c, tt.iv)
			plaintext := make([]byte, len(ciphertext))
			ofb.XORKeyStream(plaintext, ciphertext)
			if !bytes.Equal(plaintext, tt.in[:len(ciphertext)]) {
				t.Errorf("%s/%d: decrypting\nhave % x\nwant % x", test, len(ciphertext), plaintext, tt.in)
			}
		}

		if t.Failed() {
			break
		}
	}
}
Exemplo n.º 21
0
//test that same input, gives same output
func Test_ECDH_interop1(t *testing.T) {

	for i := 0; i < 1024; i++ {

		seed1 := RandByte(32)
		//seed2 := RandByte(32)

		pubkey1, seckey1 := _GenerateDeterministicKeyPair(seed1)
		pubkey2, seckey2 := GenerateDeterministicKeyPair(seed1)

		if bytes.Equal(seckey1, seckey2) == false {
			t.Fatal("deterministic seckeys do not match", i)
		}
		if bytes.Equal(pubkey1, pubkey2) == false {
			t.Fatal("deterministic pubkeys do not match", i)
		}

		puba := _ECDH(pubkey1, seckey2)
		pubb := ECDH(pubkey1, seckey2)

		if puba == nil {
			t.Fail()
		}

		if pubb == nil {
			t.Fail()
		}

		if bytes.Equal(puba, pubb) == false {
			t.Fail()
		}
	}
}
Exemplo n.º 22
0
func TestProposerSelection0(t *testing.T) {
	cs1, vss := randConsensusState(4)
	height, round := cs1.Height, cs1.Round

	newRoundCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringNewRound(), 1)
	proposalCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringCompleteProposal(), 1)

	startTestRound(cs1, height, round)

	// wait for new round so proposer is set
	<-newRoundCh

	// lets commit a block and ensure proposer for the next height is correct
	prop := cs1.GetRoundState().Validators.Proposer()
	if !bytes.Equal(prop.Address, cs1.privValidator.Address) {
		t.Fatalf("expected proposer to be validator %d. Got %X", 0, prop.Address)
	}

	// wait for complete proposal
	<-proposalCh

	rs := cs1.GetRoundState()
	signAddVoteToFromMany(types.VoteTypePrecommit, cs1, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:]...)

	// wait for new round so next validator is set
	<-newRoundCh

	prop = cs1.GetRoundState().Validators.Proposer()
	if !bytes.Equal(prop.Address, vss[1].Address) {
		t.Fatalf("expected proposer to be validator %d. Got %X", 1, prop.Address)
	}
}
Exemplo n.º 23
0
// ParseBytes parses Set-Cookie header.
//
// It is safe modifying src buffer after function return.
func (c *Cookie) ParseBytes(src []byte) error {
	c.Reset()

	var s cookieScanner
	s.b = src

	kv := &c.bufKV
	if !s.next(kv, true) {
		return errNoCookies
	}

	c.Key = append(c.Key[:0], kv.key...)
	c.Value = append(c.Value[:0], kv.value...)

	for s.next(kv, false) {
		if len(kv.key) == 0 && len(kv.value) == 0 {
			continue
		}
		switch {
		case bytes.Equal(strCookieExpires, kv.key):
			v := unsafeBytesToStr(kv.value)
			exptime, err := time.ParseInLocation(time.RFC1123, v, gmtLocation)
			if err != nil {
				return err
			}
			c.Expire = exptime
		case bytes.Equal(strCookieDomain, kv.key):
			c.Domain = append(c.Domain[:0], kv.value...)
		case bytes.Equal(strCookiePath, kv.key):
			c.Path = append(c.Path[:0], kv.value...)
		}
	}
	return nil
}
Exemplo n.º 24
0
func main() {
	doc, err := goquery.NewDocument(url)
	if err != nil {
		panic(err)
	}

	preElems := doc.Find("#mw-content-text > pre")

	if preElems.Length() != PreCount {
		panic("Did not find enough elements on the page.")
	}

	preElems.Each(func(i int, sel *goquery.Selection) {
		prees[PreType(i)] = sel.Text()
	})

	tableB := parseSBoxTable(prees[SBoxTable])
	bytesB := parseSBoxBytes(prees[SBoxBytes])

	if !bytes.Equal(tableB, bytesB) {
		panic("SBoxTable and SBoxBytes do not match")
	}

	iTableB := parseSBoxTable(prees[SBoxInvTable])
	iBytesB := parseSBoxBytes(prees[SBoxInvBytes])

	if !bytes.Equal(iTableB, iBytesB) {
		panic("SBoxInvTable and SBoxInvBytes do not match.")
	}

	fmt.Println("Everything matches.")
}
Exemplo n.º 25
0
func TestHTTPModifierURLRewrite(t *testing.T) {
	var url, newURL []byte

	rewrites := UrlRewriteMap{}

	payload := func(url []byte) []byte {
		return []byte("POST " + string(url) + " HTTP/1.1\r\nContent-Length: 7\r\nHost: www.w3.org\r\n\r\na=1&b=2")
	}

	err := rewrites.Set("/v1/user/([^\\/]+)/ping:/v2/user/$1/ping")
	if err != nil {
		t.Error("Should not error on /v1/user/([^\\/]+)/ping:/v2/user/$1/ping")
	}

	modifier := NewHTTPModifier(&HTTPModifierConfig{
		urlRewrite: rewrites,
	})

	url = []byte("/v1/user/joe/ping")
	if newURL = proto.Path(modifier.Rewrite(payload(url))); bytes.Equal(newURL, url) {
		t.Error("Request url should have been rewritten, wasn't", string(newURL))
	}

	url = []byte("/v1/user/ping")
	if newURL = proto.Path(modifier.Rewrite(payload(url))); !bytes.Equal(newURL, url) {
		t.Error("Request url should have been rewritten, wasn't", string(newURL))
	}
}
Exemplo n.º 26
0
Arquivo: images.go Projeto: djibi2/lxd
func detectCompression(fname string) ([]string, string, error) {
	f, err := os.Open(fname)
	if err != nil {
		return []string{""}, "", err
	}
	defer f.Close()

	// read header parts to detect compression method
	// bz2 - 2 bytes, 'BZ' signature/magic number
	// gz - 2 bytes, 0x1f 0x8b
	// lzma - 6 bytes, { [0x000, 0xE0], '7', 'z', 'X', 'Z', 0x00 } -
	// xy - 6 bytes,  header format { 0xFD, '7', 'z', 'X', 'Z', 0x00 }
	// tar - 263 bytes, trying to get ustar from 257 - 262
	header := make([]byte, 263)
	_, err = f.Read(header)
	if err != nil {
		return []string{""}, "", err
	}

	switch {
	case bytes.Equal(header[0:2], []byte{'B', 'Z'}):
		return []string{"-jxf"}, ".tar.bz2", nil
	case bytes.Equal(header[0:2], []byte{0x1f, 0x8b}):
		return []string{"-zxf"}, ".tar.gz", nil
	case (bytes.Equal(header[1:5], []byte{'7', 'z', 'X', 'Z'}) && header[0] == 0xFD):
		return []string{"-Jxf"}, ".tar.xz", nil
	case (bytes.Equal(header[1:5], []byte{'7', 'z', 'X', 'Z'}) && header[0] != 0xFD):
		return []string{"--lzma", "-xf"}, ".tar.lzma", nil
	case bytes.Equal(header[257:262], []byte{'u', 's', 't', 'a', 'r'}):
		return []string{"-xf"}, ".tar", nil
	default:
		return []string{""}, "", fmt.Errorf("Unsupported compression.")
	}

}
Exemplo n.º 27
0
func TestPartialRead(t *testing.T) {
	f, err := os.Open("testdata/gnu.tar")
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	defer f.Close()

	tr := NewReader(f)

	// Read the first four bytes; Next() should skip the last byte.
	hdr, err := tr.Next()
	if err != nil || hdr == nil {
		t.Fatalf("Didn't get first file: %v", err)
	}
	buf := make([]byte, 4)
	if _, err := io.ReadFull(tr, buf); err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if expected := []byte("Kilt"); !bytes.Equal(buf, expected) {
		t.Errorf("Contents = %v, want %v", buf, expected)
	}

	// Second file
	hdr, err = tr.Next()
	if err != nil || hdr == nil {
		t.Fatalf("Didn't get second file: %v", err)
	}
	buf = make([]byte, 6)
	if _, err := io.ReadFull(tr, buf); err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if expected := []byte("Google"); !bytes.Equal(buf, expected) {
		t.Errorf("Contents = %v, want %v", buf, expected)
	}
}
Exemplo n.º 28
0
func TestSectionTable(t *testing.T) {
	st := vm.SectionTable{
		vm.TEXT: []byte{0x1, 0x2, 0x3, 0x4, 0x5},
		vm.DATA: []byte{0xa, 0xb, 0xc, 0xd, 0xe, 0xf},
	}
	b := st.Bytes()
	expect := []byte{0x2,
		byte(vm.TEXT), 0x0, 0xb, 0x0, 0x5,
		byte(vm.DATA), 0x0, 0x10, 0x0, 0x6,
		0x1, 0x2, 0x3, 0x4, 0x5,
		0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
	}
	if !bytes.Equal(b, expect) {
		t.Log("expected:", expect, "got:", b)
		t.FailNow()
	}

	o := vm.NewObject()
	o.ScanSectionTable(b)
	for i, sec := range o.SecTab {
		if !bytes.Equal(st[i], sec) {
			t.Log("expected:", st[i], "got:", sec)
			t.FailNow()
		}
	}
}
Exemplo n.º 29
0
Arquivo: needle.go Projeto: wtmmac/bfs
// ParseNeedleData parse a needle data part.
func (n *Needle) ParseData(buf []byte) (err error) {
	var (
		bn       int32
		checksum uint32
	)
	n.Data = buf[:n.Size]
	bn += n.Size
	n.FooterMagic = buf[bn : bn+magicSize]
	if !bytes.Equal(n.FooterMagic, footerMagic) {
		err = errors.ErrNeedleFooterMagic
		return
	}
	bn += magicSize
	checksum = crc32.Update(0, crc32Table, n.Data)
	n.Checksum = binary.BigEndian.Uint32(buf[bn : bn+checksumSize])
	if n.Checksum != checksum {
		err = errors.ErrNeedleChecksum
		return
	}
	bn += checksumSize
	n.Padding = buf[bn : bn+n.PaddingSize]
	if !bytes.Equal(n.Padding, padding[n.PaddingSize]) {
		err = errors.ErrNeedlePadding
	}
	return
}
Exemplo n.º 30
0
func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error {
	return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
		for _, key := range keys {
			if _, err := fmt.Fprintf(rw, "touch %s %d\r\n", key, expiration); err != nil {
				return err
			}
			if err := rw.Flush(); err != nil {
				return err
			}
			line, err := rw.ReadSlice('\n')
			if err != nil {
				return err
			}
			switch {
			case bytes.Equal(line, resultTouched):
				break
			case bytes.Equal(line, resultNotFound):
				return ErrCacheMiss
			default:
				return fmt.Errorf("memcache: unexpected response line from touch: %q", string(line))
			}
		}
		return nil
	})
}