【发布时间】:2017-11-19 07:32:56
【问题描述】:
您只需阅读下面粗体字的问题即可回答整个问题,我想提供一些背景信息,以防问题不清楚
我正在重新创建一个区块链,因此需要验证创建的区块是否满足给定的要求(散列整个区块(矿工放入他的 nonce 解决方案的地方)必须小于给定的目标)。
所以我目前正在做的和正在做的事情是:
private static boolean checkDifficulty(JSONObject message) {
try {
String blockString = message.get("block").toString();
JSONObject blockPayLoad = (JSONObject) JSONValue.parse(blockString);
BlockPayload block = new BlockPayload(blockPayLoad);
BigInteger base = new BigInteger("2",16);
String difficulty = Integer.toHexString(20+block.getDifficulty());
BigInteger exponent = new BigInteger(difficulty,16);
BigInteger totalSpace = base.pow(512);
BigInteger target = totalSpace.divide(base.pow(exponent.intValueExact()));
BigInteger hashedBlock3 = new BigInteger(1,hashSHA512(blockString));
return(hashedBlock3.compareTo(target) == -1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return false;
我最初认为我可以做的是,我使用我的数据结构 BlockPayload。相关部分如下所示:
public BlockPayload(JSONObject blockPayLoad) {
this.stringRepresentation = blockPayLoad.toString();
this.type = blockPayLoad.get("type").toString();
this.transactions = blockPayLoad.get("transactions").toString();
this.timestamp = blockPayLoad.get("timestamp").toString();
this.reward = blockPayLoad.get("reward").toString();
this.difficulty = Integer.parseInt(blockPayLoad.get("difficulty").toString());
this.nonce = blockPayLoad.get("nonce").toString();
this.parent = blockPayLoad.get("parent").toString();
}
我的 toString() 返回字符串表示。 可悲的是,尝试上述相同的事情(散列字符串表示)会产生不同的结果。
我认为这是 b/c 我的 toString 没有相同的顺序,这意味着 JSONObject 中的属性顺序发生了变化。
所以这是我的问题:我能否以某种方式自定义 toString(),以保证属性按所需顺序显示?
【问题讨论】:
标签: java json tostring json-simple