Java Code Examples for com.google.protobuf.ByteString#copyFrom()

The following examples show how to use com.google.protobuf.ByteString#copyFrom() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CertGen.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
public static ByteString pemCode(byte[] encoded, String type)
{
  try
  {
    PemObject po = new PemObject(type, encoded);

    ByteArrayOutputStream b_out = new ByteArrayOutputStream();

    PemWriter w = new PemWriter( new OutputStreamWriter(b_out));

    w.writeObject(po);
    w.flush();
    w.close();

    return ByteString.copyFrom(b_out.toByteArray());
  }
  catch(java.io.IOException e)
  {
    throw new RuntimeException(e);
  }

}
 
Example 2
Source File: Duck32.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
private static ByteString convertBase32ToBytes(String encoding)
  throws ValidationException
{
  BigInteger big = new BigInteger(convertBech32ToBase32(encoding), 32);
  byte[] data = big.toByteArray();

  int data_size=HASH_BYTES + Globals.ADDRESS_SPEC_HASH_LEN;


  // Helpful biginteger might throw an extra zero byte on the front to show positive sign
  // or it might start with a lot of zeros and be short so add them back in
  int start = data.length - data_size;
  if (start >= 0)
  {
    return ByteString.copyFrom(data, start, Globals.ADDRESS_SPEC_HASH_LEN + HASH_BYTES);
  }
  else
  {
    byte[] zeros = new byte[data_size];
    int needed_zeros = data_size - data.length;
    return ByteString.copyFrom(zeros, 0, needed_zeros).concat(ByteString.copyFrom(data));
  }
}
 
Example 3
Source File: ChannelConnectionTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testClientRefusesNonCanonicalKey() throws Exception {
    ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
    PaymentChannelServer server = pair.server;
    PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, null, clientChannelProperties, pair.clientRecorder);
    client.connectionOpen();
    server.connectionOpen();
    server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
    client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
    Protos.TwoWayChannelMessage.Builder initiateMsg = Protos.TwoWayChannelMessage.newBuilder(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
    ByteString brokenKey = initiateMsg.getInitiate().getMultisigKey();
    brokenKey = ByteString.copyFrom(Arrays.copyOf(brokenKey.toByteArray(), brokenKey.size() + 1));
    initiateMsg.getInitiateBuilder().setMultisigKey(brokenKey);
    client.receiveMessage(initiateMsg.build());
    pair.clientRecorder.checkNextMsg(MessageType.ERROR);
    assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
 
Example 4
Source File: RegionManagerTest.java    From tikv-client-lib-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getRegionByKey() throws Exception {
  ByteString startKey = ByteString.copyFrom(new byte[] {1});
  ByteString endKey = ByteString.copyFrom(new byte[] {10});
  ByteString searchKey = ByteString.copyFrom(new byte[] {5});
  ByteString searchKeyNotExists = ByteString.copyFrom(new byte[] {11});
  int confVer = 1026;
  int ver = 1027;
  long regionId = 233;
  server.addGetRegionResp(
      GrpcUtils.makeGetRegionResponse(
          server.getClusterId(),
          GrpcUtils.makeRegion(
              regionId,
              GrpcUtils.encodeKey(startKey.toByteArray()),
              GrpcUtils.encodeKey(endKey.toByteArray()),
              GrpcUtils.makeRegionEpoch(confVer, ver),
              GrpcUtils.makePeer(1, 10),
              GrpcUtils.makePeer(2, 20))));
  TiRegion region = mgr.getRegionByKey(startKey);
  assertEquals(region.getId(), regionId);

  TiRegion regionToSearch = mgr.getRegionByKey(searchKey);
  assertEquals(region, regionToSearch);

  // This will in turn invoke rpc and results in an error
  // since we set just one rpc response
  try {
    mgr.getRegionByKey(searchKeyNotExists);
    fail();
  } catch (Exception e) {
  }
}
 
Example 5
Source File: ValidationTest.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
@Test
public void testChainHashCorrectString()
  throws Exception
{
  byte[] b=new byte[Globals.BLOCKCHAIN_HASH_LEN];
  ByteString bs = ByteString.copyFrom(b);

  Validation.validateChainHash(bs, "correct");
}
 
Example 6
Source File: WalletTestAccount001.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * constructor.
 */

public Account grpcQueryAccount(byte[] address,
    WalletGrpc.WalletBlockingStub blockingStubFull) {
  ByteString addressBs = ByteString.copyFrom(address);
  Account request = Account.newBuilder().setAddress(addressBs).build();
  return blockingStubFull.getAccount(request);
}
 
Example 7
Source File: ProtobufRowConversion.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected Object rawFromValue(ValueSource value) {
    BigDecimalWrapper wrapper = TBigDecimal.getWrapper(value, type);
    int precision = type.attribute(DecimalAttribute.PRECISION);
    int scale = type.attribute(DecimalAttribute.SCALE);
    return ByteString.copyFrom(ConversionHelperBigDecimal.bytesFromObject(wrapper.asBigDecimal(), precision, scale));
}
 
Example 8
Source File: UUIDUtil.java    From jesos with Apache License 2.0 5 votes vote down vote up
public static ByteString uuidBytes(final UUID uuid)
{
    final ByteBuffer longBuffer = ByteBuffer.allocate(16).order(ByteOrder.BIG_ENDIAN);
    longBuffer.mark();
    longBuffer.putLong(uuid.getMostSignificantBits());
    longBuffer.putLong(uuid.getLeastSignificantBits());
    longBuffer.reset();
    return ByteString.copyFrom(longBuffer);
}
 
Example 9
Source File: BaggageImplTest.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSerialization() {
    BaggageImpl b = new BaggageImpl();
    ByteString myname = ByteString.copyFrom("namespace".getBytes());
    ByteString myname2 = ByteString.copyFrom("namespace2".getBytes());
    ByteString v1 = ByteString.copyFrom("k1".getBytes());
    ByteString v2 = ByteString.copyFrom("k2".getBytes());
    ByteString v3 = ByteString.copyFrom("k3".getBytes());
    ByteString v4 = ByteString.copyFrom("k4".getBytes());
    b.add(myname, v1, v2);
    b.add(myname, v2, null);
    b.add(myname, v3, v1);
    b.add(myname, v2, v1);
    b.add(myname2, v1, v4);
    byte[] s = b.toByteArray();
    b.add(myname, v4, v4);
    BaggageImpl b2 = BaggageImpl.deserialize(s);
    // recovery of serialization
    assertTrue(b2.get(myname, v2).contains(v1));
    assertFalse(b2.get(myname, v2).contains(null));
    assertTrue(b2.get(myname, v3).contains(v1));
    assertTrue(b2.get(myname, v1).contains(v2));
    assertTrue(b2.get(myname2, v1).contains(v4));
    // deserialize creates a new copy
    assertTrue(b2.get(myname, v4).isEmpty());
    // edge cases
    assertNull(BaggageImpl.deserialize((byte[]) null));
    assertNull(BaggageImpl.deserialize(new byte[0]));
    assertNull(BaggageImpl.deserialize(new byte[1]));
    assertNull(BaggageImpl.deserialize("not valid".getBytes()));
    assertNull(BaggageImpl.deserialize(BaggageMessage.newBuilder().build().toByteArray()));
    // null for empty baggage
    assertEquals(0, new BaggageImpl().toByteArray().length);
}
 
Example 10
Source File: WalletTestAssetIssue004.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) {
  ByteString addressBs = ByteString.copyFrom(address);
  Account request = Account.newBuilder().setAddress(addressBs).build();
  return blockingStubFull.getAccount(request);
}
 
Example 11
Source File: DbKeyTestUtils.java    From exonum-java-binding with Apache License 2.0 4 votes vote down vote up
/** Creates a 32-byte ByteString key from the bit prefix. */
public static ByteString keyByteStringFromString(String prefix) {
  byte[] key = keyFromString(prefix);
  return ByteString.copyFrom(key);
}
 
Example 12
Source File: AbstractPublisher.java    From pubsub with Apache License 2.0 4 votes vote down vote up
/** Creates a string message of a certain size. */
private ByteString createMessage(int msgSize) {
  byte[] payloadArray = new byte[msgSize];
  Arrays.fill(payloadArray, (byte) 'A');
  return ByteString.copyFrom(payloadArray);
}
 
Example 13
Source File: TraceProtoUtilsTest.java    From opentelemetry-java with Apache License 2.0 4 votes vote down vote up
@Test
public void toProtoTraceId() {
  ByteString expected = ByteString.copyFrom(TRACE_ID_BYTES);
  assertThat(TraceProtoUtils.toProtoTraceId(TRACE_ID)).isEqualTo(expected);
}
 
Example 14
Source File: MessagePayloadSerializerRaw.java    From stateful-functions with Apache License 2.0 4 votes vote down vote up
@Override
public Payload serialize(@Nonnull Object what) {
  byte[] bytes = (byte[]) what;
  ByteString bs = ByteString.copyFrom(bytes);
  return Payload.newBuilder().setPayloadBytes(bs).build();
}
 
Example 15
Source File: ManagerTest.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void doNotSwitch()
    throws ValidateSignatureException, ContractValidateException, ContractExeException,
    UnLinkedBlockException, ValidateScheduleException, BadItemException,
    ItemNotFoundException, HeaderNotFound, AccountResourceInsufficientException,
    TransactionExpirationException, TooBigTransactionException,
    DupTransactionException, BadBlockException,
    TaposException, BadNumberBlockException, NonCommonBlockException,
    ReceiptCheckErrException, VMIllegalException, TooBigTransactionResultException {
  Args.setParam(new String[]{"--witness"}, Constant.TEST_NET_CONF);
  long size = dbManager.getBlockStore().size();
  System.out.print("block store size:" + size + "\n");
  String key = "27216755ffd8726184b428971834df395030578461e7b5b3967b68697ca9925c";
  byte[] privateKey = ByteArray.fromHexString(key);
  final ECKey ecKey = ECKey.fromPrivate(privateKey);
  byte[] address = ecKey.getAddress();
  WitnessWrapper witnessWrapper = new WitnessWrapper(ByteString.copyFrom(address));
  dbManager.addWitness(ByteString.copyFrom(address));
  dbManager.generateBlock(witnessWrapper, 1565913600000L, privateKey, false, false);

  Map<ByteString, String> addressToProvateKeys = addTestWitnessAndAccount();

  long num = dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber();
  BlockWrapper blockWrapper0 =
      createTestBlockWrapper(
              1565913600000L + 3000,
          num + 1,
          dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash()
              .getByteString(),
          addressToProvateKeys);

  BlockWrapper blockWrapper1 =
      createTestBlockWrapper(
              1565913600000L + 3001,
          num + 1,
          dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash()
              .getByteString(),
          addressToProvateKeys);

  logger.info("******block0:" + blockWrapper0);
  logger.info("******block1:" + blockWrapper1);

  dbManager.pushBlock(blockWrapper0);
  dbManager.pushBlock(blockWrapper1);
  context.getBean(KhaosDatabase.class).removeBlk(dbManager.getBlockIdByNum(num));
  Exception exception = null;

  BlockWrapper blockWrapper2 =
      createTestBlockWrapper(
              1565913600000L + 6000,
          num + 2, blockWrapper1.getBlockId().getByteString(), addressToProvateKeys);
  logger.info("******block2:" + blockWrapper2);
  try {
    dbManager.pushBlock(blockWrapper2);
  } catch (NonCommonBlockException e) {
    logger.info("do not switch fork");
    Assert.assertNotNull(dbManager.getBlockStore().get(blockWrapper0.getBlockId().getBytes()));
    Assert.assertEquals(blockWrapper0.getBlockId(),
        dbManager.getBlockStore().get(blockWrapper0.getBlockId().getBytes()).getBlockId());
    Assert.assertEquals(blockWrapper0.getBlockId(),
        dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash());
    exception = e;
  }

  if (exception == null) {
    throw new IllegalStateException();
  }

  BlockWrapper blockWrapper3 =
      createTestBlockWrapper(1565913600000L + 9000,
          dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1,
          dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash()
              .getByteString(),
          addressToProvateKeys);
  logger.info("******block3:" + blockWrapper3);
  dbManager.pushBlock(blockWrapper3);

  Assert.assertEquals(blockWrapper3.getBlockId(),
      dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash());
  Assert.assertEquals(blockWrapper3.getBlockId(),
      dbManager.getBlockStore()
          .get(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash()
              .getBytes())
          .getBlockId());

  BlockWrapper blockWrapper4 =
      createTestBlockWrapper(1565913600000L + 12000,
          dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1,
          blockWrapper3.getBlockId().getByteString(), addressToProvateKeys);
  logger.info("******block4:" + blockWrapper4);
  dbManager.pushBlock(blockWrapper4);

  Assert.assertEquals(blockWrapper4.getBlockId(),
      dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash());
  Assert.assertEquals(blockWrapper4.getBlockId(),
      dbManager.getBlockStore()
          .get(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderHash()
              .getBytes())
          .getBlockId());
}
 
Example 16
Source File: ProtobufCreator.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
private Object getValue(Builder builder, FieldDescriptor field, Message defaultInstance, ExtensionRegistryWrapper extensionRegistry) {
  switch (field.getJavaType()) {
    case INT:
      return r.nextInt();
    case LONG:
      return r.nextLong();
    case FLOAT:
      return r.nextFloat();
    case DOUBLE:
      return r.nextDouble();
    case BOOLEAN:
      return r.nextBoolean();
    case STRING:
      String available = "abcdefghijklmnopqrstuvwxyz0123456789";
      int length = r.nextInt(20) + 1;
      String value = "";
      for (int i = 0; i < length; i++) {
        value += available.charAt(r.nextInt(available.length()));
      }
      return value;
    case BYTE_STRING:
      byte[] bytes = new byte[r.nextInt(20) + 1];
      r.nextBytes(bytes);
      return ByteString.copyFrom(bytes);
    case ENUM:
      List<EnumValueDescriptor> values = field.getEnumType().getValues();
      return values.get(r.nextInt(values.size()));
    case MESSAGE:
      final Class<? extends Message> subMessageType;
      if (field.isExtension()) {
        subMessageType = defaultInstance.getClass();
      } else {
        subMessageType = builder.newBuilderForField(field).getDefaultInstanceForType().getClass();
      }

      // Handle recursive relationships by returning a partially populated proto (better than an infinite loop)
      if (partiallyBuilt.containsKey(subMessageType)) {
        return partiallyBuilt.get(subMessageType).build();
      } else {
        return create(subMessageType, extensionRegistry);
      }
    default:
      throw new IllegalArgumentException("Unrecognized field type: " + field.getJavaType());
  }
}
 
Example 17
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private Object handlePrimitive(JsonParser parser, FieldDescriptor field) throws IOException {
    Object value = null;

    JsonToken token = parser.getCurrentToken();

    if (token.equals(JsonToken.VALUE_NULL)) {
        return value;
    }

    switch (field.getType()) {
        case INT32:
        case SINT32:
        case SFIXED32:
        	value = parser.getIntValue();
            break;

        case INT64:
        case SINT64:
        case SFIXED64:
        	value = parser.getLongValue();
            break;

        case UINT32:
        case FIXED32:
        	long valueLong = parser.getLongValue();
        	if (valueLong < 0 || valueLong > MAX_UINT_VALUE) {
        		throw new NumberFormatException("Number must be positive: " + valueLong);
        	}
        	value = (int) valueLong;
            break;

        case UINT64:
        case FIXED64:
        	BigInteger valueBigInt = parser.getBigIntegerValue();
            // valueBigInt < 0 || valueBigInt > MAX_ULONG_VALUE
        	if (valueBigInt.compareTo(BigInteger.ZERO) == -1 || valueBigInt.compareTo(MAX_ULONG_VALUE) == 1) {
        		throw new NumberFormatException("Number must be positive: " + valueBigInt);
        	}
        	value = valueBigInt.longValue();
            break;

        case FLOAT:
        	value = parser.getFloatValue();
            break;

        case DOUBLE:
        	value = parser.getDoubleValue();
            break;

        case BOOL:
        	value = parser.getBooleanValue();
            break;

        case STRING:
        	value = parser.getText();
            break;

        case BYTES:
        	value = ByteString.copyFrom(parser.getBinaryValue());
            break;

        case ENUM: {
            EnumDescriptor enumType = field.getEnumType();
            if (token.equals(JsonToken.VALUE_NUMBER_INT)) {
                int number = parser.getIntValue();
                value = enumType.findValueByNumber(number);
                if (value == null) {
                    throw new RuntimeException("Enum type \""
                    		+ enumType.getFullName()
                    		+ "\" has no value with number "
                    		+ number + ".");
                }
            } else {
                String id = parser.getText();
                value = enumType.findValueByName(id);
                if (value == null) {
                	throw new RuntimeException("Enum type \""
                			+ enumType.getFullName()
                			+ "\" has no value named \""
                			+ id + "\".");
                }
            }
            break;
        }

        case MESSAGE:
        case GROUP:
            throw new RuntimeException("Can't get here.");
    }
    return value;
}
 
Example 18
Source File: Cmp.java    From jetcd with Apache License 2.0 4 votes vote down vote up
public Cmp(ByteSequence key, Op compareOp, CmpTarget<?> target) {
    this.key = ByteString.copyFrom(key.getBytes());
    this.op = compareOp;
    this.target = target;
}
 
Example 19
Source File: TransactionWrapper.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void addSign(byte[] privateKey, AccountStore accountStore)
        throws PermissionException, SignatureException, SignatureFormatException {
    Transaction.Contract contract = this.transaction.getRawData().getContract(0);
    int permissionId = contract.getPermissionId();
    byte[] owner = getOwner(contract);
    AccountWrapper account = accountStore.get(owner);
    if (account == null) {
        throw new PermissionException("Account is not exist!");
    }
    Permission permission = account.getPermissionById(permissionId);
    if (permission == null) {
        throw new PermissionException("permission isn't exit");
    }
    if (permissionId != 0) {
        if (permission.getType() != PermissionType.Active) {
            throw new PermissionException("Permission type is error");
        }
        //check oprations
        if (!Wallet.checkPermissionOprations(permission, contract)) {
            throw new PermissionException("Permission denied");
        }
    }
    List<ByteString> approveList = new ArrayList<>();
    ECKey ecKey = ECKey.fromPrivate(privateKey);
    byte[] address = ecKey.getAddress();
    if (this.transaction.getSignatureCount() > 0) {
        checkWeight(permission, this.transaction.getSignatureList(), this.getRawHash().getBytes(),
                approveList);
        if (approveList.contains(ByteString.copyFrom(address))) {
            throw new PermissionException(Wallet.encode58Check(address) + " had signed!");
        }
    }

    long weight = getWeight(permission, address);
    if (weight == 0) {
        throw new PermissionException(
                ByteArray.toHexString(privateKey) + "'s address is " + Wallet
                        .encode58Check(address) + " but it is not contained of permission.");
    }
    ECDSASignature signature = ecKey.sign(getRawHash().getBytes());
    ByteString sig = ByteString.copyFrom(signature.toByteArray());
    this.transaction = this.transaction.toBuilder().addSignature(sig).build();
}
 
Example 20
Source File: ChainHash.java    From snowblossom with Apache License 2.0 4 votes vote down vote up
public ChainHash(byte[] b)
{
  this(ByteString.copyFrom(b));
}