001package org.consensusj.bitcoin.json.pojo; 002 003import com.fasterxml.jackson.annotation.JsonCreator; 004import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 005import com.fasterxml.jackson.annotation.JsonProperty; 006import org.bitcoinj.base.Sha256Hash; 007 008import java.util.List; 009import java.util.Optional; 010 011/** 012 * 013 */ 014public class ChainTip { 015 private final int height; 016 private final Sha256Hash hash; 017 private final int branchlen; 018 private final String status; 019 020 @JsonCreator 021 public ChainTip(@JsonProperty("height") int height, 022 @JsonProperty("hash") Sha256Hash hash, 023 @JsonProperty("branchlen") int branchlen, 024 @JsonProperty("status") String status) { 025 this.height = height; 026 this.hash = hash; 027 this.branchlen = branchlen; 028 this.status = status; 029 } 030 031 public int getHeight() { 032 return height; 033 } 034 035 public Sha256Hash getHash() { 036 return hash; 037 } 038 039 public int getBranchlen() { 040 return branchlen; 041 } 042 043 public String getStatus() { 044 return status; 045 } 046 047 /** 048 * Find the active chain tip if there is one 049 * @param chainTips the list to search 050 * @return non-empty optional if active is found, empty optional if not found 051 */ 052 public static Optional<ChainTip> findActiveChainTip(List<ChainTip> chainTips) { 053 return chainTips.stream().filter(tip -> tip.getStatus().equals("active")).findFirst(); 054 } 055 056 public static ChainTip findActiveChainTipOrElseThrow(List<ChainTip> chainTips) { 057 return findActiveChainTip(chainTips).orElseThrow(() -> new RuntimeException("No active ChainTip")); 058 } 059 060 /** 061 * Construct an "active" {@link ChainTip} 062 * 063 * @param height best block height 064 * @param hash best block hash 065 * @return current "active" ChainTip 066 */ 067 public static ChainTip ofActive(int height, Sha256Hash hash) { 068 return new ChainTip(height, hash, 0, "active"); 069 } 070}