src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking) { this.privateNetworking = privateNetworking; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); } | @Test public void testPrivateNetworking() { TemplateOptions options = new DigitalOcean2TemplateOptions().privateNetworking(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getPrivateNetworking(), true); } |
Car { private Car() { if (servoCommand == null) { Environment env = Config.getEnvironment(); String servo_CommandConfig="servoblaster"; try { servo_CommandConfig = env.getString(Config.SERVO_COMMAND); } catch (Exception e) { ErrorHandler.getInstance().handle(e); } switch (servo_CommandConfig) { case "adafruit": try { servoCommand=new AdaFruit(); LOG.info("using AdaFruit ServoCommand handling"); } catch (Exception e) { ErrorHandler.getInstance().handle(e); } break; default: servoCommand = new ServoBlaster(); } } engine = new Engine(this, new EngineMap(servoCommand)); steering = new Steering(this, new SteeringMap(servoCommand)); led = new Led(new LedMap(servoCommand)); } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; } | @Test public void testCar() throws Exception { Car car = getCar(); car.setPowerOn(); int tvalues[]= {-1,120,1000}; for (int tvalue:tvalues) { car.turn(new ServoPosition(tvalue,tvalue*10)); } int dvalues[]= {-1,150,1000}; for (int dvalue:dvalues) { car.drive(new ServoPosition(dvalue,dvalue*10)); } if (debug) servoCommand.showLog(); } |
Configuration { public Configuration(String graphFilePath, boolean readInis) { this.graphFilePath = graphFilePath; setGraph(TinkerGraph.open()); File graphFile = getGraphFile(); if (readInis) { fromIni(); write(); } else { if (graphFile.exists()) { read(graphFile); } } } Configuration(String graphFilePath, boolean readInis); Configuration(); String getGraphFilePath(); void setGraphFilePath(String graphFilePath); void fromIni(); void addEnv(Environment env); TinkerGraph getGraph(); void setGraph(TinkerGraph graph); GraphTraversalSource g(); File getGraphFile(); void read(File graphFile); void write(File graphFile); String asString(); Map<String, Environment> getEnvironments(); Environment getEnvironmentFromVertex(Vertex v); void write(); static String STORE_MODE; static String STORE_EXTENSION; } | @Test public void testConfiguration() throws Exception { Configuration config=getMockConfiguration(); long nodeCount = config.g().V().count().next().longValue(); assertEquals(1,nodeCount); config.write(); assertTrue(config.getGraphFile().canRead()); config.getGraphFile().delete(); } |
Environment { private Environment() { runningOnRaspberryPi = isPi(); } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; } | @Test public void testEnvironment() throws Exception { String ip = "1.2.3.4"; int port = 8080; File propFile = setProperties(Config.REMOTECAR_HOST, ip, Config.WEBCONTROL_PORT, "" + port); Environment env = Config.getEnvironment(); String piIp = env.getString(Config.REMOTECAR_HOST); assertEquals(ip, piIp); assertFalse(env.isPi()); assertEquals(port, env.getInteger(Config.WEBCONTROL_PORT)); propFile.delete(); } |
Environment { public List<String> getMyIpAddresses() { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .map(iface -> Collections.list(iface.getInetAddresses())) .flatMap(Collection::stream).map(InetAddress::getHostAddress) .collect(Collectors.toList()); } catch (SocketException e) { LOG.error("Error while determining IP addresses: ", e); return null; } } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; } | @Test public void testGetMyIpAddresses() { List<String> ips = Environment.getInstance().getMyIpAddresses(); assertNotNull(ips); assertTrue(ips.size() > 1); } |
Environment { public static void mock() { Environment.from("../rc-drivecontrol/src/test/resources/dukes/dukes.ini"); } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; } | @Test public void testMock() throws Exception { Environment.mock(); JsonObject jo = Environment.getInstance().asJsonObject(); String json = jo.toString(); if (debug) System.out.println(json); Environment env = Config.getEnvironment(); assertEquals(-20.0,env.getDouble(Config.WHEEL_MAX_LEFT_ANGLE),0.001); } |
ClusterStarter { public void deployVerticles(AbstractVerticle... verticles) throws Exception { DeploymentOptions deploymentOptions = this.getDeployMentOptions(true); if (vertx == null) { this.clusteredVertx(resultHandler -> { vertx = resultHandler.result(); if (vertx == null) { ErrorHandler.getInstance().handle(new RuntimeException( "vertx not available resultHandler result is null")); } this.deployVerticles(deploymentOptions, verticles); }); } else { this.deployVerticles(deploymentOptions, verticles); } } Vertx getVertx(); void prepare(); void configureCluster(String clusterHostname,String publicHost); void clusteredVertx(Handler<AsyncResult<Vertx>> resultHandler); DeploymentOptions getDeployMentOptions(boolean worker); void deployVerticles(AbstractVerticle... verticles); VertxOptions getOptions(); void undeployVerticle(DukesVerticle verticle); String getHostname(); void setHostname(String hostname); static final int MAX_START_TIME; } | @Test public void testClusterStarter() throws Exception { Environment.mock(); ClusterStarter starter = new ClusterStarter(); TestVerticle testVerticle = new TestVerticle(); starter.deployVerticles(testVerticle); testVerticle.waitStatus(Status.started, ClusterStarter.MAX_START_TIME, 10); int minLoops=5; while (testVerticle.counter <=minLoops) { Thread.sleep(TestVerticle.TEST_INTERVAL_MS); } } |
ErrorHandler { public static String getStackTraceText(Throwable th) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); String exceptionText = sw.toString(); return exceptionText; } static String getStackTraceText(Throwable th); } | @Test public void testErrorHandler() { String trace=null; try { throw new Exception("oops - a problem"); } catch (Throwable th) { trace=ErrorHandler.getStackTraceText(th); } assertNotNull(trace); assertTrue(trace.contains("oops - a problem")); assertTrue(trace.contains("TestErrorHandler.java:18")); } |
ROI { public ROI(String name,double rx, double ry, double rw, double rh) { this.name=name; this.rx = rx; this.ry = ry; this.rw = rw; this.rh = rh; } ROI(String name,double rx, double ry, double rw, double rh); Rect roiRect(Size base); Mat region(Mat image); String toString(); } | @Test public void testROI() throws Exception { if (!isTravis()) { NativeLibrary.load(); File imgRoot = new File(testPath); assertTrue(imgRoot.isDirectory()); Mat image = Imgcodecs.imread(testPath + "dukes_roi_test_image.jpg"); assertNotNull(image); assertEquals(960, image.height()); assertEquals(1280, image.width()); ROI rois[] = { new ROI("all", 0, 0, 1, 1), new ROI("far", 0, 0, 1, 0.5), new ROI("near", 0, 0.5, 1, 0.5), new ROI("left", 0, 0, 0.5, 1), new ROI("right", 0.5, 0, 0.5, 1) }; for (ROI roi : rois) { System.out.println(roi); Mat roiImage = roi.region(image); if (debug) System.out.println(String.format("%10s: %4d x %4d", roi.name, roiImage.width(), roiImage.height())); assertEquals(roiImage.width(), image.width() * roi.rw, 0.1); assertEquals(roiImage.height(), image.height() * roi.rh, 0.1); this.writeImage("dukes_roi_" + roi.name, roiImage); } } } |
StraightLaneNavigator extends TinkerPopDatabase implements Navigator { public StraightLaneNavigator() { this(DEFAULT_TIME_WINDOW); } StraightLaneNavigator(); StraightLaneNavigator(int timeWindow); DukesVerticle getSender(); void setSender(DukesVerticle sender); Vertex addToGraph(LaneDetectionResult ldr); @Override LaneDetectionResult fromJsonObject(JsonObject jo); boolean cmdOk(AngleRange angleRange, int minFound); void setTime(LaneDetectionResult ldr); void analyzeAngleRanges(int timeWindow, boolean showDebug); @Override JsonObject getNavigationInstruction(LaneDetectionResult ldr); JsonObject steerCommand(Double angle); @Override void navigateWithInstruction(JsonObject navigationInstruction); @Override void navigateWithMessage(Message<JsonObject> ldrMessage); @Override void navigateWithLaneDetectionResult(LaneDetectionResult ldr); @Override void videoStopped(VideoInfo videoInfo); static int COMMAND_LOOP_INTERVAL; static final int MAX_DURATION_NO_LINES_DETECTED; static final int DEFAULT_TIME_WINDOW; } | @Test public void testStraightLaneNavigator() { LaneDetectionResult ldrs[] = { getLdr(1, 0, -45., 0., 45.), getLdr(2, 100, -46., 1., 46.), getLdr(3, 200, -47., 0., 47.) }; StraightLaneNavigator nav = new StraightLaneNavigator(); for (LaneDetectionResult ldr : ldrs) nav.getNavigationInstruction(ldr); long nodeCount = nav.g().V().count().next().longValue(); assertEquals(3, nodeCount); } |
StraightLaneNavigator extends TinkerPopDatabase implements Navigator { @Override public JsonObject getNavigationInstruction(LaneDetectionResult ldr) { JsonObject message = null; if (this.emergencyStopActivated) return message; setTime(ldr); Vertex ldrVertex=addToGraph(ldr); boolean showDebug = true; analyzeAngleRanges(timeWindow, showDebug); if (currentTime - startTime > MAX_DURATION_NO_LINES_DETECTED && stopRangeLeft.count + stopRangeRight.count == 0 || emergencyStopActivated) { this.emergencyStopActivated = true; return ActionVerticle.emergencyStopCommand(); } int MIN_FOUND_PER_TIMEWINDOW = 3; AngleRange navigateRange = null; if (middleRange.count >= MIN_FOUND_PER_TIMEWINDOW) { navigateRange = courseRange; } else { navigateRange = leftRange.count > rightRange.count ? leftRange : rightRange; } if (this.cmdOk(navigateRange, MIN_FOUND_PER_TIMEWINDOW)) { double angle = navigateRange.steer(); String msg = ldr.debugInfo() + String.format("\nsteer by %s: %s", navigateRange.name, Line.angleString(angle)); LOG.debug(msg); ldrVertex.property("steer",angle); ldrVertex.property("steerBy",navigateRange.name); ldrVertex.property("debugInfo",msg); tsLatestCommand = currentTime; message = steerCommand(angle); } return message; } StraightLaneNavigator(); StraightLaneNavigator(int timeWindow); DukesVerticle getSender(); void setSender(DukesVerticle sender); Vertex addToGraph(LaneDetectionResult ldr); @Override LaneDetectionResult fromJsonObject(JsonObject jo); boolean cmdOk(AngleRange angleRange, int minFound); void setTime(LaneDetectionResult ldr); void analyzeAngleRanges(int timeWindow, boolean showDebug); @Override JsonObject getNavigationInstruction(LaneDetectionResult ldr); JsonObject steerCommand(Double angle); @Override void navigateWithInstruction(JsonObject navigationInstruction); @Override void navigateWithMessage(Message<JsonObject> ldrMessage); @Override void navigateWithLaneDetectionResult(LaneDetectionResult ldr); @Override void videoStopped(VideoInfo videoInfo); static int COMMAND_LOOP_INTERVAL; static final int MAX_DURATION_NO_LINES_DETECTED; static final int DEFAULT_TIME_WINDOW; } | @Test public void testFromVideo() throws Exception { NativeLibrary.load(); Navigator nav = new StraightLaneNavigator(); String testUrl = "http: ImageFetcher imageFetcher = new ImageFetcher(testUrl); imageFetcher.open(); int frameIndex = 0; int maxFrameIndex = 300; while (frameIndex < maxFrameIndex && imageFetcher.hasNext() && !imageFetcher.isClosed()) { Image image = imageFetcher.fetch(); frameIndex = image.getFrameIndex(); System.out.println(frameIndex); if (imageFetcher.hasNext()) { LaneDetector laneDetector = LaneDetector.getDefault(); LaneDetectionResult ldr = laneDetector.detect(image); if (debug) System.out.println(ldr.debugInfo()); JsonObject navJo = nav.getNavigationInstruction(ldr); if (navJo != null) System.out.println(navJo.encodePrettily()); } } imageFetcher.close(); long nodeCount = nav.g().V().count().next().longValue(); assertEquals(maxFrameIndex, nodeCount); } |
WatchDog extends DukesVerticle { public WatchDog(Car car) throws Exception { super(Characters.FLASH); this.car = car; Environment env = Config.getEnvironment(); HEARTBEAT_INTERVAL_MS=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS); MAX_MISSED_BEATS=env.getInteger(Config.WATCHDOG_MAX_MISSED_BEATS); } WatchDog(Car car); @Override void start(); } | @Test public void testWatchDog() throws Exception { ClusterStarter clusterStarter=new ClusterStarter(); Car car=TestCar.getCar(); Environment env = Config.getEnvironment(); int heartBeatInterval=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS); assertEquals(20,heartBeatInterval); int maxMissedBeats=env.getInteger(Config.WATCHDOG_MAX_MISSED_BEATS); assertEquals(2,maxMissedBeats); WatchDog watchDog=new WatchDog(car); clusterStarter.deployVerticles(watchDog); watchDog.waitStatus(Status.started,20000,10); Vertx vertx=clusterStarter.getVertx(); assertNotNull(vertx); assertEquals(watchDog.getVertx(),vertx); watchDog.send(Characters.FLASH,"type","heartbeat"); int loops=0; while(!car.powerIsOn() && loops<=100) { Thread.sleep(10); loops++; } assertTrue(loops<100); LOG.info(String.format("car powered on after %3d msecs",loops*10)); Thread.sleep(heartBeatInterval*(maxMissedBeats+3)); assertTrue(!car.powerIsOn()); } |
Car { public Steering getSteering() { return steering; } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; } | @Test public void testSteering() throws Exception { Car car = getCar(); Steering steering = car.getSteering(); steering.center(); ServoPosition cpos = steering.getSteeringMap().getCurrentPosition(); System.out.println(cpos); } |
Car { public Led getLed() { return led; } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; } | @Test public void testLed() throws Exception { Car car = getCar(); Led led = car.getLed(); led.statusLedOn(); led.statusLedOff(); if (debug) servoCommand.showLog(); } |
ImageFetcher { public ImageFetcher(String source) { this.source = source; } ImageFetcher(String source); double getFps(); void setFps(double fps); int getFrameIndex(); boolean isStaticImage(); void setStaticImage(boolean staticImage); boolean open(); void close(); long waitForNextFrame(); Image fetch(); Image createNextImage(Mat frame, long currentMillis); Observable<Image> toObservable(); boolean hasNext(); boolean isClosed(); public boolean debug; static double DEFAULT_FPS; } | @Test public void testImageFetcher() { ImageFetcher imageFetcher = getTestImageFetcher(); imageFetcher.debug=debug; Image image; do { image= imageFetcher.fetch(); } while (image != null); if (debug) { String msg = String.format("%s has %d frames", testSource, imageFetcher.getFrameIndex()); System.out.println(msg); } assertEquals(488, imageFetcher.getFrameIndex()); } |
ImageFetcher { public Observable<Image> toObservable() { Observable<Image> observable = Observable .create(new ObservableOnSubscribe<Image>() { @Override public void subscribe(ObservableEmitter<Image> observableEmitter) throws Exception { hasNext=true; while (hasNext && !isClosed()) { final Image image = ImageFetcher.this.fetch(); if (hasNext) { if (debug && frameIndex % Math.round(getFps()) == 0) { String msg = String.format("->%6d:%4.0fx%4.0f", frameIndex, size.width, size.height); LOG.info(msg); } observableEmitter.onNext(image); } } observableEmitter.onComplete(); } }); return observable; } ImageFetcher(String source); double getFps(); void setFps(double fps); int getFrameIndex(); boolean isStaticImage(); void setStaticImage(boolean staticImage); boolean open(); void close(); long waitForNextFrame(); Image fetch(); Image createNextImage(Mat frame, long currentMillis); Observable<Image> toObservable(); boolean hasNext(); boolean isClosed(); public boolean debug; static double DEFAULT_FPS; } | @Test public void testImageFetcherObservable() { ImageFetcher imageFetcher = getTestImageFetcher(); Observable<Image> imageObservable = imageFetcher.toObservable(); ImageObserver imageObserver = new ImageObserver(); imageObserver.debug=debug; imageObservable.subscribe(imageObserver); assertNull(imageObserver.error); assertTrue(imageObserver.completed); assertEquals(768,imageObserver.cols); assertEquals(576,imageObserver.rows); }
@Test public void testImageFetcherObservableSample() { ImageFetcher imageFetcher = getTestImageFetcher(); Observable<Image> imageObservable = imageFetcher.toObservable(); ImageObserver imageObserver = new ImageObserver(); imageObserver.debug=debug; imageObservable.sample(40, TimeUnit.MILLISECONDS).subscribe(imageObserver); assertNull(imageObserver.error); assertTrue(imageObserver.completed); assertEquals(768,imageObserver.cols); assertEquals(576,imageObserver.rows); } |
RemoteCar extends DukesVerticle { public RemoteCar() { super(Characters.GENERAL_LEE); } RemoteCar(); @Override void start(); void parseArguments(String[] args); void mainInstance(String... args); static void main(String... args); @Option(name = "-ph", aliases = { "--publichost" }, usage = "hostname") String publicHost; } | @Test public void testRemoteCar() throws Exception { Environment.mock(); ClusterStarter clusterStarter = new ClusterStarter(); clusterStarter.prepare(); RemoteCar remoteCar = new RemoteCar(); clusterStarter.deployVerticles(remoteCar); DukesVerticle.debug=true; remoteCar.waitStatus(Status.started, ClusterStarter.MAX_START_TIME, 10); JsonObject configJo=Config.getEnvironment().asJsonObject(); remoteCar.send(Characters.GENERAL_LEE,configJo); Thread.sleep(ClusterStarter.MAX_START_TIME); } |
RemoteCar extends DukesVerticle { public static void main(String... args) { RemoteCar remoteCar = new RemoteCar(); remoteCar.mainInstance(args); } RemoteCar(); @Override void start(); void parseArguments(String[] args); void mainInstance(String... args); static void main(String... args); @Option(name = "-ph", aliases = { "--publichost" }, usage = "hostname") String publicHost; } | @Test public void testRemoteCarCommandLine() { Environment.mock(); String args[]= {}; RemoteCar.main(args); } |
PerspectiveShift implements UnaryOperator<Mat> { @Override public Mat apply(Mat srcImage) { Mat destImage = new Mat(); Imgproc.warpPerspective(srcImage, destImage, perspectiveTransform, srcImage.size()); return destImage; } PerspectiveShift(Polygon imagePolygon, Polygon worldPolygon); @Override Mat apply(Mat srcImage); } | @Test public void testChessboard() { CameraMatrix matrix = new CameraMatrix(7, 7); Mat chessboard = Imgcodecs.imread(testPath + "dukes_chessBoard008.png"); Point[] corners = matrix.findOuterChessBoardCornerPoints(chessboard); assertNotNull(corners); assertEquals(4, corners.length); if (debug) { System.out.print("corners: "); String delim = ""; for (int i = 0; i < 4; i++) { System.out.print( String.format("(%.1f,%.1f)%s", corners[i].x, corners[i].y, delim)); delim = ","; if (i == 2) delim = "\n"; } } writeImage("chessBoardCorners", chessboard); Size size = chessboard.size(); Polygon imagePolygon = new ImagePolygon(size, 0, 0, 1, 0, 1, 1, 0, 1); Polygon worldPolygon = new ImagePolygon(corners); PerspectiveShift perspectiveShift = new PerspectiveShift(imagePolygon, worldPolygon); if (debug) { System.out.println("image: " + perspectiveShift.imagePoints); System.out.println("world: " + perspectiveShift.worldPoints); } Mat shifted = perspectiveShift.apply(chessboard); writeImage("shiftedChessBoard", shifted); }
@Test public void testTransform() throws Exception { Mat original = Imgcodecs.imread(testPath + "dukes_livingroom.jpeg"); ROI roi = new ROI("near", 0, 0.4, 1, 0.6); Mat image = roi.region(original); Polygon imagePolygon = new ImagePolygon(image.size(), 0, 0, 1, 0, 1, 1, 0, 1); Polygon worldPolygon = new ImagePolygon(image.size(), 0.30, 0.20, 0.80, 0.28, 0.96, 0.62, 0.15, 0.46); PerspectiveShift perspectiveShift = new PerspectiveShift(imagePolygon, worldPolygon); Mat shifted = perspectiveShift.apply(image); if (debug) { System.out.println("worldp:" + perspectiveShift.worldPolygon); System.out.println("world: " + perspectiveShift.worldPoints); writeImage("roiImage", image); writeImage("shiftedImage", shifted); } } |
RSAKeyPair { public static RSAKeyPair fromExponents(byte[] e, byte[] p, byte[] q) { final BigInteger eInt = BigIntegers.fromUnsignedByteArray(e), pInt = BigIntegers.fromUnsignedByteArray(p), qInt = BigIntegers.fromUnsignedByteArray(q), nInt = pInt.multiply(qInt), mInt = pInt.subtract(BigInteger.ONE).multiply(qInt.subtract(BigInteger.ONE)), dInt = eInt.modInverse(mInt), dPInt = dInt.remainder(pInt.subtract(BigInteger.ONE)), dQInt = dInt.remainder(qInt.subtract(BigInteger.ONE)), qInvInt = qInt.modInverse(pInt); final byte[] n = BigIntegers.asUnsignedByteArray(nInt), d = BigIntegers.asUnsignedByteArray(dInt), dP = BigIntegers.asUnsignedByteArray(dPInt), dQ = BigIntegers.asUnsignedByteArray(dQInt), qInv = BigIntegers.asUnsignedByteArray(qInvInt); return new RSAKeyPair(n, e, d, p, q, dP, dQ, qInv); } RSAKeyPair(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q, byte[] dP, byte[] dQ, byte[] qInv); static RSAKeyPair fromExponents(byte[] e, byte[] p, byte[] q); final byte[] n; final byte[] e; final byte[] d; final byte[] p; final byte[] q; final byte[] dP; final byte[] dQ; final byte[] qInv; } | @Test public void fromExponents() throws Exception { RSAKeyPair rsaPair = RSAKeyPair.fromExponents(rsaSpec.e, rsaSpec.p, rsaSpec.q); assertArrayEquals(rsaPair.n, rsaSpec.n); assertArrayEquals(rsaPair.e, rsaSpec.e); assertArrayEquals(rsaPair.d, rsaSpec.d); assertArrayEquals(rsaPair.p, rsaSpec.p); assertArrayEquals(rsaPair.q, rsaSpec.q); assertArrayEquals(rsaPair.dP, rsaSpec.dP); assertArrayEquals(rsaPair.dQ, rsaSpec.dQ); assertArrayEquals(rsaPair.qInv, rsaSpec.qInv); } |
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } | @Test public void checkLimitRequestsForKey() throws Exception { PrivateKey myKey = TestKeys.privateKey(3); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(true)); Main main = mm.get(0); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute() * 2; i++) { Contract testContract = new Contract(myKey); testContract.seal(); assertTrue(testContract.isOk()); Set<PublicKey> ownerKeys = new HashSet(); Collection<PrivateKey> keys = Do.listOf(myKey); keys.stream().forEach(key -> ownerKeys.add(key.getPublicKey())); Contract stepaU = InnerContractsService.createFreshU(100000000, ownerKeys); stepaU.check(); stepaU.traceErrors(); client.register(stepaU.getPackedTransaction()); Set<PrivateKey> keySet = new HashSet<>(); keySet.addAll(keys); Parcel parcel = ContractsService.createParcel(testContract, stepaU, 150, keySet); client.registerParcel(parcel.pack()); } long seconds = ZonedDateTime.now().toEpochSecond() % 60; if (seconds > 57) Thread.currentThread().sleep(3000); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute(); i++) System.out.println(">> storage rate: " + client.storageGetRate()); String exception = ""; try { client.storageGetRate(); } catch (Exception e) { System.out.println("Client exception: " + e.toString()); exception = e.getMessage(); } assertEquals(exception, "ClientError: COMMAND_FAILED exceeded the limit of requests for key per minute," + " please call again after a while"); System.out.println("Wait 1 munite..."); Thread.currentThread().sleep(60000); seconds = ZonedDateTime.now().toEpochSecond() % 60; if (seconds > 57) Thread.currentThread().sleep(3000); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute(); i++) System.out.println(">> uns rate: " + client.unsRate()); exception = ""; try { client.unsRate(); } catch (Exception e) { System.out.println("Client exception: " + e.toString()); exception = e.getMessage(); } assertEquals(exception, "ClientError: COMMAND_FAILED exceeded the limit of requests for key per minute," + " please call again after a while"); System.out.println("Wait 1 munite..."); Thread.currentThread().sleep(60000); seconds = ZonedDateTime.now().toEpochSecond() % 60; if (seconds > 57) Thread.currentThread().sleep(3000); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute(); i++) client.getStats(90); exception = ""; try { client.getStats(90); } catch (Exception e) { System.out.println("Client exception: " + e.toString()); exception = e.getMessage(); } assertEquals(exception, "ClientError: COMMAND_FAILED exceeded the limit of requests for key per minute," + " please call again after a while"); mm.forEach(x -> x.shutdown()); }
@Test public void checkUnlimitRequestsForKey() throws Exception { PrivateKey myKey = TestKeys.privateKey(3); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(true)); Main main = mm.get(0); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Set<PublicKey> ownerKeys = new HashSet(); Set<PrivateKey> keys = new HashSet(); keys.add(myKey); ownerKeys.add(myKey.getPublicKey()); Contract payment = InnerContractsService.createFreshU(100000000, ownerKeys); payment.check(); payment.traceErrors(); client.register(payment.getPackedTransaction()); Thread.currentThread().sleep(5000); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(false)); long seconds = ZonedDateTime.now().toEpochSecond() % 60; if (seconds > 57) Thread.currentThread().sleep(3000); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute(); i++) System.out.println(">> storage rate: " + client.storageGetRate()); String exception = ""; try { client.storageGetRate(); } catch (Exception e) { System.out.println("Client exception: " + e.toString()); exception = e.getMessage(); } assertEquals(exception, "ClientError: COMMAND_FAILED exceeded the limit of requests for key per minute," + " please call again after a while"); Contract unlimitContract = ContractsService.createRateLimitDisablingContract( myKey.getPublicKey(), payment, main.config.getRateLimitDisablingPayment(), keys); unlimitContract.check(); unlimitContract.traceErrors(); assertTrue(unlimitContract.isOk()); ItemResult itemResult = client.register(unlimitContract.getPackedTransaction()); Thread.currentThread().sleep(5000); itemResult = client.getState(unlimitContract.getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute() * 2; i++) System.out.println(">> storage rate: " + client.storageGetRate()); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute() * 2; i++) System.out.println(">> uns rate: " + client.unsRate()); for (int i = 0; i < main.config.getLimitRequestsForKeyPerMinute() * 2; i++) client.getStats(90); mm.forEach(x -> x.shutdown()); }
@Test public void checkUnlimitRequestsBadParam() throws Exception { PrivateKey myKey = TestKeys.privateKey(3); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(true)); Main main = mm.get(0); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Set<PublicKey> ownerKeys = new HashSet(); Set<PrivateKey> keys = new HashSet(); keys.add(myKey); ownerKeys.add(myKey.getPublicKey()); Contract payment = InnerContractsService.createFreshU(100000000, ownerKeys); payment.check(); payment.traceErrors(); client.register(payment.getPackedTransaction()); Thread.currentThread().sleep(5000); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(false)); Contract unlimitContract = ContractsService.createRateLimitDisablingContract( myKey.getPublicKey(), payment, 1, keys); Contract unlimitContract1 = ContractsService.createRateLimitDisablingContract( myKey.getPublicKey(), payment, main.config.getRateLimitDisablingPayment() + 1, keys); unlimitContract.check(); unlimitContract.traceErrors(); assertTrue(unlimitContract.isOk()); unlimitContract1.check(); unlimitContract1.traceErrors(); assertTrue(unlimitContract1.isOk()); System.out.println("Processing cost " + unlimitContract.getProcessedCostU()); ItemResult itemResult = client.register(unlimitContract.getPackedTransaction()); Thread.currentThread().sleep(5000); System.out.println(); assertEquals((itemResult.errors.get(0).getMessage()), "Payment for setting unlimited requests" + " must be 5U"); itemResult = client.getState(unlimitContract.getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); itemResult = client.register(unlimitContract1.getPackedTransaction()); Thread.currentThread().sleep(5000); System.out.println(); assertEquals((itemResult.errors.get(0).getMessage()), "Payment for setting unlimited requests" + " must be 5U"); itemResult = client.getState(unlimitContract1.getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void checkUnlimitRequestsBadKey() throws Exception { PrivateKey myKey = TestKeys.privateKey(3); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(true)); Main main = mm.get(0); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Set<PublicKey> ownerKeys = new HashSet(); Set<PrivateKey> keys = new HashSet(); keys.add(myKey); ownerKeys.add(myKey.getPublicKey()); Contract payment = InnerContractsService.createFreshU(100, ownerKeys); payment.check(); payment.traceErrors(); client.register(payment.getPackedTransaction()); Thread.currentThread().sleep(5000); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(false)); Contract unlimitContract = ContractsService.createRateLimitDisablingContract( myKey.getPublicKey(), payment, main.config.getRateLimitDisablingPayment(), keys); byte[] packedKey = unlimitContract.getTransactional().getData().getBinary("unlimited_key"); PublicKey key = new PublicKey(packedKey); assertFalse((packedKey == null) || ((key == null))); assertEquals(unlimitContract.getRevoking().get(0).getStateData().getIntOrThrow("transaction_units") - unlimitContract.getStateData().getIntOrThrow("transaction_units"), 5); unlimitContract.check(); unlimitContract.traceErrors(); assertTrue(unlimitContract.isOk()); unlimitContract.getTransactional().getData().set("unlimited_key", "badkeybadkeybadkeybadkey"); unlimitContract.seal(); client.register(unlimitContract.getPackedTransaction()); Thread.currentThread().sleep(5000); System.out.println(); ItemResult itemResult = client.getState(unlimitContract.getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void checkLimitRequestsTestU() throws Exception { PrivateKey myKey = TestKeys.privateKey(3); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(true)); Main main = mm.get(0); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Set<PublicKey> ownerKeys = new HashSet(); Set<PrivateKey> keys = new HashSet(); keys.add(myKey); ownerKeys.add(myKey.getPublicKey()); Contract payment = InnerContractsService.createFreshU(100, ownerKeys, true); payment.check(); payment.traceErrors(); client.register(payment.getPackedTransaction()); Thread.currentThread().sleep(5000); ItemResult itemResult = client.getState(payment.getId()); System.out.println(">> state payment: " + itemResult); System.out.println(payment.getStateData().getString("transaction_units")); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(myKey); payment.getStateData().set("transaction_units", 0); payment.setOwnerKeys(ownerKeys); payment.addSignerKey(myKey); payment.seal(); client.register(payment.getPackedTransaction()); Thread.currentThread().sleep(5000); itemResult = client.getState(payment.getId()); System.out.println(">> state payment: " + itemResult); System.out.println(payment.getStateData().getString("transaction_units")); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(false)); Contract unlimitContract = ContractsService.createRateLimitDisablingContract( myKey.getPublicKey(), payment, main.config.getRateLimitDisablingPayment(), keys); client.register(unlimitContract.getPackedTransaction()); Thread.currentThread().sleep(5000); itemResult = client.getState(unlimitContract.getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowComplete() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract completedEscrow = ContractsService.completeEscrowContract(escrow); assertEquals(completedEscrow.getStateData().getString("status", "null"), "completed"); completedEscrow.addSignatureToSeal(issuerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(customerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(executorPrivateKeys); completedEscrow.check(); completedEscrow.traceErrors(); itemResult = client.register(completedEscrow.getPackedTransaction(), 5000); System.out.println("completedEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(executorPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(completedEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowCancel() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract canceledEscrow = ContractsService.cancelEscrowContract(escrow); assertEquals(canceledEscrow.getStateData().getString("status", "null"), "canceled"); canceledEscrow.addSignatureToSeal(issuerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(customerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(arbitratorPrivateKeys); canceledEscrow.check(); canceledEscrow.traceErrors(); itemResult = client.register(canceledEscrow.getPackedTransaction(), 5000); System.out.println("canceledEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(customerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(canceledEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowCompleteFail() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract completedEscrow = ContractsService.completeEscrowContract(escrow); assertEquals(completedEscrow.getStateData().getString("status", "null"), "completed"); completedEscrow.addSignatureToSeal(issuerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(executorPrivateKeys); completedEscrow.check(); completedEscrow.traceErrors(); itemResult = client.register(completedEscrow.getPackedTransaction(), 5000); System.out.println("completedEscrow : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(executorPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(completedEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowCancelFail() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract canceledEscrow = ContractsService.cancelEscrowContract(escrow); assertEquals(canceledEscrow.getStateData().getString("status", "null"), "canceled"); canceledEscrow.addSignatureToSeal(issuerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(customerPrivateKeys); canceledEscrow.check(); canceledEscrow.traceErrors(); itemResult = client.register(canceledEscrow.getPackedTransaction(), 5000); System.out.println("canceledEscrow : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(customerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(canceledEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowCompleteAndTakePaymentFail() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract completedEscrow = ContractsService.completeEscrowContract(escrow); assertEquals(completedEscrow.getStateData().getString("status", "null"), "completed"); completedEscrow.addSignatureToSeal(issuerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(customerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(executorPrivateKeys); completedEscrow.check(); completedEscrow.traceErrors(); itemResult = client.register(completedEscrow.getPackedTransaction(), 5000); System.out.println("completedEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(customerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(completedEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowCancelAndTakePaymentFail() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract canceledEscrow = ContractsService.cancelEscrowContract(escrow); assertEquals(canceledEscrow.getStateData().getString("status", "null"), "canceled"); canceledEscrow.addSignatureToSeal(issuerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(customerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(arbitratorPrivateKeys); canceledEscrow.check(); canceledEscrow.traceErrors(); itemResult = client.register(canceledEscrow.getPackedTransaction(), 5000); System.out.println("canceledEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(executorPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(canceledEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowInternalComplete() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createInternalEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getStateData().getString("status", "null"), "opened"); escrow.getStateData().set("description", "Simple escrow"); escrow.getStateData().set("percent", 10); escrow.seal(); payment = ContractsService.modifyPaymentForEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract completedEscrow = ContractsService.completeEscrowContract(escrow); assertEquals(completedEscrow.getStateData().getString("status", "null"), "completed"); completedEscrow.addSignatureToSeal(issuerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(customerPrivateKeys); completedEscrow = Contract.fromPackedTransaction(completedEscrow.getPackedTransaction()); completedEscrow.addSignatureToSeal(executorPrivateKeys); assertEquals(completedEscrow.getStateData().getString("description", "null"), "Simple escrow"); assertEquals(completedEscrow.getStateData().getLong("percent", 0), 10); completedEscrow.check(); completedEscrow.traceErrors(); itemResult = client.register(completedEscrow.getPackedTransaction(), 5000); System.out.println("completedEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(executorPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(completedEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowInternalCancel() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createInternalEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getStateData().getString("status", "null"), "opened"); escrow.getStateData().set("description", "Simple escrow"); escrow.getStateData().set("percent", 10); escrow.seal(); payment = ContractsService.modifyPaymentForEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract canceledEscrow = ContractsService.cancelEscrowContract(escrow); assertEquals(canceledEscrow.getStateData().getString("status", "null"), "canceled"); canceledEscrow.addSignatureToSeal(issuerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(customerPrivateKeys); canceledEscrow = Contract.fromPackedTransaction(canceledEscrow.getPackedTransaction()); canceledEscrow.addSignatureToSeal(arbitratorPrivateKeys); assertEquals(canceledEscrow.getStateData().getString("description", "null"), "Simple escrow"); assertEquals(canceledEscrow.getStateData().getLong("percent", 0), 10); canceledEscrow.check(); canceledEscrow.traceErrors(); itemResult = client.register(canceledEscrow.getPackedTransaction(), 5000); System.out.println("canceledEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(customerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(canceledEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowCompleteWithRepack() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); Contract internalEscrow = escrow.getNew().get(0); internalEscrow.getStateData().set("description", "Simple internal escrow"); internalEscrow.getStateData().set("percent", 20); internalEscrow.seal(); escrow = ContractsService.createExternalEscrowContract(internalEscrow, issuerPrivateKeys); escrow.getStateData().set("description", "Simple external escrow"); escrow.getStateData().set("percent", 20); escrow.seal(); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract completedEscrow = ContractsService.completeEscrowContract(escrow); assertEquals(completedEscrow.getStateData().getString("status", "null"), "completed"); completedEscrow.addSignatureToSeal(issuerPrivateKeys); completedEscrow.addSignatureToSeal(customerPrivateKeys); completedEscrow.addSignatureToSeal(executorPrivateKeys); assertEquals(completedEscrow.getStateData().getString("description", "null"), "Simple internal escrow"); assertEquals(completedEscrow.getStateData().getLong("percent", 0), 20); assertEquals(escrow.getStateData().getString("description", "null"), "Simple external escrow"); assertEquals(escrow.getStateData().getLong("percent", 0), 20); completedEscrow.check(); completedEscrow.traceErrors(); itemResult = client.register(completedEscrow.getPackedTransaction(), 5000); System.out.println("completedEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(executorPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(completedEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowReOpenFail() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract canceledEscrow = ContractsService.cancelEscrowContract(escrow); assertEquals(canceledEscrow.getStateData().getString("status", "null"), "canceled"); canceledEscrow.addSignatureToSeal(issuerPrivateKeys); canceledEscrow.addSignatureToSeal(customerPrivateKeys); canceledEscrow.addSignatureToSeal(arbitratorPrivateKeys); canceledEscrow.check(); canceledEscrow.traceErrors(); itemResult = client.register(canceledEscrow.getPackedTransaction(), 5000); System.out.println("canceledEscrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract revisionEscrow = canceledEscrow.createRevision(issuerPrivateKeys); revisionEscrow.getStateData().set("status", "opened"); revisionEscrow.seal(); revisionEscrow.addSignatureToSeal(customerPrivateKeys); revisionEscrow.addSignatureToSeal(executorPrivateKeys); revisionEscrow.addSignatureToSeal(arbitratorPrivateKeys); itemResult = client.register(revisionEscrow.getPackedTransaction(), 5000); System.out.println("revisionEscrow : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); revisionEscrow = canceledEscrow.createRevision(issuerPrivateKeys); revisionEscrow.getStateData().set("status", "completed"); revisionEscrow.seal(); revisionEscrow.addSignatureToSeal(customerPrivateKeys); revisionEscrow.addSignatureToSeal(executorPrivateKeys); revisionEscrow.addSignatureToSeal(arbitratorPrivateKeys); itemResult = client.register(revisionEscrow.getPackedTransaction(), 5000); System.out.println("revisionEscrow : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(customerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(canceledEscrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void ecsrowTakePaymentFail() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PrivateKey> customerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> arbitratorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PrivateKey> executorPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(3))); Set<PublicKey> issuerPublicKeys = new HashSet<>(); for (PrivateKey pk : issuerPrivateKeys) { issuerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> customerPublicKeys = new HashSet<>(); for (PrivateKey pk : customerPrivateKeys) { customerPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> executorPublicKeys = new HashSet<>(); for (PrivateKey pk : executorPrivateKeys) { executorPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> arbitratorPublicKeys = new HashSet<>(); for (PrivateKey pk : arbitratorPrivateKeys) { arbitratorPublicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, customerPublicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); payment = payment.createRevision(customerPrivateKeys); Contract escrow = ContractsService.createEscrowContract(issuerPrivateKeys, customerPublicKeys, executorPublicKeys, arbitratorPublicKeys); assertEquals(escrow.getDefinition().getData().getString("EscrowOrigin", "null"), escrow.getNew().get(0).getOrigin().toBase64String()); assertEquals(escrow.getNew().get(0).getStateData().getString("status", "null"), "opened"); boolean result = ContractsService.addPaymentToEscrowContract(escrow, payment, customerPrivateKeys, customerPublicKeys, executorPublicKeys); assertTrue(result); assertTrue(payment.findReferenceByName("return_payment_to_customer", "transactional") != null); assertTrue(payment.findReferenceByName("send_payment_to_executor", "transactional") != null); escrow.check(); escrow.traceErrors(); itemResult = client.register(escrow.getPackedTransaction(), 5000); System.out.println("escrow : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = main.node.waitItem(payment.getId(), 8000); assertEquals(ItemState.APPROVED, itemResult.state); Contract newPayment = ContractsService.takeEscrowPayment(issuerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(escrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); newPayment = ContractsService.takeEscrowPayment(customerPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(escrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); newPayment = ContractsService.takeEscrowPayment(executorPrivateKeys, payment); newPayment.getTransactionPack().addReferencedItem(escrow); newPayment.check(); newPayment.traceErrors(); itemResult = client.register(newPayment.getPackedTransaction(), 5000); System.out.println("newPayment : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void testPermanetMode() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); Set<PrivateKey> privateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PublicKey> publicKeys = new HashSet<>(); for (PrivateKey pk : privateKeys) { publicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, publicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); for (int i = 1; i < 4; i++) { byte[] keeping = mm.get(i).node.getLedger().getKeepingItem(payment.getId()); assertNotNull(keeping); assertTrue(Arrays.equals(payment.getPackedTransaction(), keeping)); } Contract baseContract = Contract.fromDslFile(ROOT_PATH + "DeLoreanOwnership.yml"); PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); baseContract.setExpiresAt(ZonedDateTime.now().plusSeconds(5)); baseContract.addSignerKey(manufacturePrivateKey); baseContract.seal(); baseContract.check(); baseContract.traceErrors(); itemResult = client.register(baseContract.getPackedTransaction(), 5000); System.out.println("contract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); for (int i = 1; i < 4; i++) { byte[] keeping = mm.get(i).node.getLedger().getKeepingItem(baseContract.getId()); assertNotNull(keeping); assertTrue(Arrays.equals(baseContract.getPackedTransaction(), keeping)); } Thread.sleep(8000); itemResult = client.getState(baseContract.getId()); System.out.println("expired : " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); for (int i = 1; i < 4; i++) { byte[] keeping = mm.get(i).node.getLedger().getKeepingItem(baseContract.getId()); assertNotNull(keeping); assertTrue(Arrays.equals(baseContract.getPackedTransaction(), keeping)); } main.config.setIsFreeRegistrationsAllowedFromYaml(false); Contract parcelContract = Contract.fromDslFile(ROOT_PATH + "LamborghiniOwnership.yml"); parcelContract.setOwnerKeys(TestKeys.privateKey(1).getPublicKey()); parcelContract.addSignerKey(manufacturePrivateKey); parcelContract.seal(); parcelContract.check(); parcelContract.traceErrors(); Parcel parcel = createParcelWithFreshU(client, parcelContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); for (int i = 1; i < 4; i++) { byte[] keeping = mm.get(i).node.getLedger().getKeepingItem(parcel.getPayloadContract().getId()); assertNotNull(keeping); assertTrue(Arrays.equals(parcel.getPayloadContract().getPackedTransaction(), keeping)); } Contract revisionContract = parcelContract.createRevision(manufacturePrivateKey); revisionContract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); revisionContract.addSignerKey(TestKeys.privateKey(1)); revisionContract.seal(); revisionContract.check(); revisionContract.traceErrors(); parcel = createParcelWithFreshU(client, revisionContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); for (int i = 1; i < 4; i++) { byte[] keeping_root = mm.get(i).node.getLedger().getKeepingItem(parcelContract.getId()); byte[] keeping_revision = mm.get(i).node.getLedger().getKeepingItem(revisionContract.getId()); assertNotNull(keeping_root); assertNotNull(keeping_revision); assertTrue(Arrays.equals(parcelContract.getPackedTransaction(), keeping_root)); assertTrue(Arrays.equals(revisionContract.getPackedTransaction(), keeping_revision)); } Contract revokeContract = ContractsService.createRevocation(revisionContract, manufacturePrivateKey); revokeContract.seal(); revokeContract.check(); revokeContract.traceErrors(); parcel = createParcelWithFreshU(client, revokeContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revocation : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); itemResult = client.getState(revisionContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); for (int i = 1; i < 4; i++) { byte[] keeping_root = mm.get(i).node.getLedger().getKeepingItem(parcelContract.getId()); byte[] keeping_revision = mm.get(i).node.getLedger().getKeepingItem(revisionContract.getId()); byte[] keeping_revoke = mm.get(i).node.getLedger().getKeepingItem(revokeContract.getId()); assertNotNull(keeping_root); assertNotNull(keeping_revision); assertNotNull(keeping_revoke); assertTrue(Arrays.equals(parcelContract.getPackedTransaction(), keeping_root)); assertTrue(Arrays.equals(revisionContract.getPackedTransaction(), keeping_revision)); assertTrue(Arrays.equals(revokeContract.getPackedTransaction(), keeping_revoke)); } HashSet<PrivateKey> own = new HashSet<>(Do.listOf(manufacturePrivateKey)); Contract rootContract = ContractsService.createTokenContract(own, new HashSet<>(Do.listOf(manufacturePrivateKey.getPublicKey())), "10000"); rootContract.seal(); parcel = createParcelWithFreshU(client, rootContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); List<Contract> splitres = ContractsService.createSplitJoin(Do.listOf(rootContract), Do.listOf("100", "200", "300", "400"), Do.listOf( TestKeys.publicKey(1).getShortAddress(), TestKeys.publicKey(2).getShortAddress(), TestKeys.publicKey(3).getShortAddress(), TestKeys.publicKey(4).getShortAddress()), own, "amount"); parcel = createParcelWithFreshU(client, splitres.get(0), privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("split : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); List<HashId> ids = client.getChildren(rootContract.getId(), 5).getListOrThrow("ids"); System.out.println("children : " + ids); List<HashId> ids2 = client.getChildren(rootContract.getId(), 3).getListOrThrow("ids"); List<HashId> ids3 = client.getChildren(rootContract.getId(), 3, 3).getListOrThrow("ids"); HashSet set1 = new HashSet(ids); HashSet set2 = new HashSet(ids2); set2.addAll(ids3); assertEquals(set1, set2); assertEquals(ids.size(), splitres.size()); assertTrue(splitres.stream().allMatch(c -> ids.contains(c.getId()))); mm.forEach(x -> x.shutdown()); }
@Test public void testPermanetModeSearchTags() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); for (int i = 0; i < 4; i++) { mm.get(i).config.setIsFreeRegistrationsAllowedFromYaml(true); assertTrue(mm.get(i).config.isPermanetMode()); } main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); String value1 = HashId.createRandom().toBase64String(); String value2 = HashId.createRandom().toBase64String(); String value3 = HashId.createRandom().toBase64String(); Contract c = new Contract(TestKeys.privateKey(1)); c.getDefinition().getData().put("search_tags",Binder.of("tag1",value1,"tag2",value2,"tag3",value3)); c.seal(); assertEquals(client.register(c.getPackedTransaction(),8000).state,ItemState.APPROVED); Binder res = client.getContract(null, Binder.of("tag1", value1, "any_of", Binder.of("tag2", value2, "tag3", "AAA")), 10, 0); assertEquals(res.getListOrThrow("contractIds").size(),1); res = client.getContract(null, Binder.of("tag1", value1, "all_of", Binder.of("tag2", value2, "tag3", "AAA")), 10, 0); assertNull(res); res = client.getContract(null, Binder.of("tag1", "AAA", "all_of", Binder.of("tag2", value2, "tag3", value3)), 10, 0); assertNull(res); res = client.getContract(null, Binder.of("tag1", value1, "all_of", Binder.of("tag2", value2, "tag3", value3)), 10, 0); assertEquals(res.getListOrThrow("contractIds").size(),1); mm.forEach(x -> x.shutdown()); }
@Test public void testPermanetApiGetBodyGood() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); Set<PrivateKey> privateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PublicKey> publicKeys = new HashSet<>(); for (PrivateKey pk : privateKeys) { publicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, publicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); byte[] keeping = client.getBody(payment.getId()); assertNotNull(keeping); assertTrue(Arrays.equals(payment.getPackedTransaction(), keeping)); Contract baseContract = Contract.fromDslFile(ROOT_PATH + "DeLoreanOwnership.yml"); PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); baseContract.setExpiresAt(ZonedDateTime.now().plusSeconds(5)); baseContract.addSignerKey(manufacturePrivateKey); baseContract.seal(); baseContract.check(); baseContract.traceErrors(); itemResult = client.register(baseContract.getPackedTransaction(), 5000); System.out.println("contract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); keeping = client.getBody(baseContract.getId()); assertNotNull(keeping); assertTrue(Arrays.equals(baseContract.getPackedTransaction(), keeping)); Thread.sleep(8000); itemResult = client.getState(baseContract.getId()); System.out.println("expired : " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); keeping = client.getBody(baseContract.getId()); assertNotNull(keeping); assertTrue(Arrays.equals(baseContract.getPackedTransaction(), keeping)); main.config.setIsFreeRegistrationsAllowedFromYaml(false); Contract parcelContract = Contract.fromDslFile(ROOT_PATH + "LamborghiniOwnership.yml"); parcelContract.setOwnerKeys(TestKeys.privateKey(1).getPublicKey()); parcelContract.addSignerKey(manufacturePrivateKey); parcelContract.seal(); parcelContract.check(); parcelContract.traceErrors(); Parcel parcel = createParcelWithFreshU(client, parcelContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); keeping = client.getBody(parcel.getPayloadContract().getId()); assertNotNull(keeping); assertTrue(Arrays.equals(parcel.getPayloadContract().getPackedTransaction(), keeping)); Contract revisionContract = parcelContract.createRevision(manufacturePrivateKey); revisionContract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); revisionContract.addSignerKey(TestKeys.privateKey(1)); revisionContract.seal(); revisionContract.check(); revisionContract.traceErrors(); parcel = createParcelWithFreshU(client, revisionContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); byte[] keeping_root = client.getBody(parcelContract.getId()); byte[] keeping_revision = client.getBody(revisionContract.getId()); assertNotNull(keeping_root); assertNotNull(keeping_revision); assertTrue(Arrays.equals(parcelContract.getPackedTransaction(), keeping_root)); assertTrue(Arrays.equals(revisionContract.getPackedTransaction(), keeping_revision)); Contract revokeContract = ContractsService.createRevocation(revisionContract, manufacturePrivateKey); revokeContract.seal(); revokeContract.check(); revokeContract.traceErrors(); parcel = createParcelWithFreshU(client, revokeContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revocation : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); itemResult = client.getState(revisionContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); keeping_root = client.getBody(parcelContract.getId()); keeping_revision = client.getBody(revisionContract.getId()); byte[] keeping_revoke = client.getBody(revokeContract.getId()); assertNotNull(keeping_root); assertNotNull(keeping_revision); assertNotNull(keeping_revoke); assertTrue(Arrays.equals(parcelContract.getPackedTransaction(), keeping_root)); assertTrue(Arrays.equals(revisionContract.getPackedTransaction(), keeping_revision)); assertTrue(Arrays.equals(revokeContract.getPackedTransaction(), keeping_revoke)); mm.forEach(x -> x.shutdown()); }
@Test public void testPermanetApiGetBodyNull() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); Set<PrivateKey> privateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PublicKey> publicKeys = new HashSet<>(); for (PrivateKey pk : privateKeys) { publicKeys.add(pk.getPublicKey()); } Contract payment = InnerContractsService.createFreshU(100, publicKeys, true); payment.check(); payment.traceErrors(); ItemResult itemResult = client.register(payment.getPackedTransaction(), 5000); System.out.println("payment : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); Contract baseContract = Contract.fromDslFile(ROOT_PATH + "DeLoreanOwnership.yml"); PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); baseContract.setExpiresAt(ZonedDateTime.now().plusSeconds(5)); baseContract.addSignerKey(manufacturePrivateKey); baseContract.seal(); baseContract.check(); baseContract.traceErrors(); itemResult = client.register(baseContract.getPackedTransaction(), 5000); System.out.println("contract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); byte[] stranger = client.getBody(HashId.createRandom()); assertNull(stranger); mm.forEach(x -> x.shutdown()); }
@Test public void testPermanetApiGetBodyResync() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); Set<PrivateKey> privateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PublicKey> publicKeys = new HashSet<>(); for (PrivateKey pk : privateKeys) { publicKeys.add(pk.getPublicKey()); } Contract parcelContract = Contract.fromDslFile(ROOT_PATH + "LamborghiniOwnership.yml"); PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); parcelContract.setOwnerKeys(TestKeys.privateKey(1).getPublicKey()); parcelContract.addSignerKey(manufacturePrivateKey); parcelContract.seal(); parcelContract.check(); parcelContract.traceErrors(); Parcel parcel = createParcelWithFreshU(client, parcelContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); ItemResult itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); HashId origin = parcelContract.getId(); Db db = ((PostgresLedger) main.node.getLedger()).getDb(); try (PreparedStatement statement = db.statement("delete from kept_items where origin = ?")) { statement.setBytes(1, origin.getDigest()); db.updateWithStatement(statement); } catch (Exception e) { e.printStackTrace(); throw e; } assertNull(main.node.getLedger().getKeepingItem(parcelContract.getId())); byte[] keeping = client.getBody(parcel.getPayloadContract().getId()); assertNotNull(keeping); assertTrue(Arrays.equals(parcel.getPayloadContract().getPackedTransaction(), keeping)); Contract revisionContract = parcelContract.createRevision(manufacturePrivateKey); revisionContract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); revisionContract.addSignerKey(TestKeys.privateKey(1)); revisionContract.seal(); revisionContract.check(); revisionContract.traceErrors(); parcel = createParcelWithFreshU(client, revisionContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); try (PreparedStatement statement = db.statement("delete from kept_items where origin = ?")) { statement.setBytes(1, origin.getDigest()); db.updateWithStatement(statement); } catch (Exception e) { e.printStackTrace(); throw e; } assertNull(main.node.getLedger().getKeepingItem(parcelContract.getId())); assertNull(main.node.getLedger().getKeepingItem(revisionContract.getId())); byte[] keeping_root = client.getBody(parcelContract.getId()); byte[] keeping_revision = client.getBody(revisionContract.getId()); assertNotNull(keeping_root); assertNotNull(keeping_revision); assertTrue(Arrays.equals(parcelContract.getPackedTransaction(), keeping_root)); assertTrue(Arrays.equals(revisionContract.getPackedTransaction(), keeping_revision)); Thread.sleep(2000); mm.forEach(x -> x.shutdown()); }
@Test public void testGetContractAPIforOneActive() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); Set<PrivateKey> privateKeys = new HashSet<>(asList(TestKeys.privateKey(0))); Set<PublicKey> publicKeys = new HashSet<>(); for (PrivateKey pk : privateKeys) { publicKeys.add(pk.getPublicKey()); } PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); Contract parcelContract = Contract.fromDslFile(ROOT_PATH + "LamborghiniOwnership.yml"); parcelContract.setOwnerKeys(TestKeys.privateKey(1).getPublicKey()); parcelContract.addSignerKey(manufacturePrivateKey); parcelContract.seal(); parcelContract.check(); parcelContract.traceErrors(); Parcel parcel = createParcelWithFreshU(client, parcelContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); ItemResult itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Thread.sleep(2000); HashId origin = parcelContract.getId(); Binder result = client.getContract(origin); byte[] keeping_root = result.getBytesOrThrow("packedContract").toArray(); assertTrue(Arrays.equals(parcelContract.getPackedTransaction(), keeping_root)); Contract revisionContract = parcelContract.createRevision(manufacturePrivateKey); revisionContract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); revisionContract.addSignerKey(TestKeys.privateKey(1)); revisionContract.seal(); revisionContract.check(); revisionContract.traceErrors(); parcel = createParcelWithFreshU(client, revisionContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); result = client.getContract(origin); byte[] keeping_revision = result.getBytesOrThrow("packedContract").toArray(); assertTrue(Arrays.equals(revisionContract.getPackedTransaction(), keeping_revision)); result = client.getContract(revisionContract.getId()); assertNull(result); Contract revokeContract = ContractsService.createRevocation(revisionContract, manufacturePrivateKey); revokeContract.seal(); revokeContract.check(); revokeContract.traceErrors(); parcel = createParcelWithFreshU(client, revokeContract, privateKeys); client.registerParcelWithState(parcel.pack(), 8000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println("revocation : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); itemResult = client.getState(parcelContract.getId()); System.out.println("revision : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); itemResult = client.getState(revisionContract.getId()); System.out.println("root : " + itemResult); assertEquals(ItemState.REVOKED, itemResult.state); Thread.sleep(2000); result = client.getContract(origin); assertNull(result); mm.forEach(x -> x.shutdown()); }
@Test public void testGetContractAPIforManyActive() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); main.config.setPermanetMode(false); assertTrue(main.config.isPermanetMode()); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Set<PrivateKey> issuerPrivateKeys2 = new HashSet<>(asList(TestKeys.privateKey(2))); List<Contract> splits = new ArrayList<>(); Integer amountTokens = 1000; Contract tokenContract = ContractsService.createTokenContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("1000")); tokenContract.check(); tokenContract.traceErrors(); HashId origin = tokenContract.getId(); ItemResult itemResult = client.register(tokenContract.getPackedTransaction(), 5000); System.out.println("tokenContract : " + itemResult + " = " + amountTokens.toString()); assertEquals(ItemState.APPROVED, itemResult.state); for (Integer i = 1; i < 41; i++) { Contract contractRemainder = ContractsService.createSplit(tokenContract, new BigDecimal(i), "amount", issuerPrivateKeys2, true); Contract contractSplit = contractRemainder.getNew().get(0); amountTokens -= i; splits.add(contractSplit); itemResult = client.register(contractRemainder.getPackedTransaction(), 5000); System.out.println("contractRemainder : " + itemResult + " = " + amountTokens.toString()); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(amountTokens.toString(), contractRemainder.getStateData().get("amount").toString()); assertEquals(i.toString(), contractSplit.getStateData().get("amount").toString()); assertEquals(ItemState.REVOKED, main.node.waitItem(tokenContract.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(contractRemainder.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(contractSplit.getId(), 5000).state); tokenContract = contractRemainder; } Binder result = client.getContract(origin); List<byte[]> allKeepingIds = result.getListOrThrow("contractIds"); assertFalse(result.containsKey("packedContract")); assertEquals(allKeepingIds.size(), splits.size() + 1); final HashId hash = tokenContract.getId(); assertTrue(allKeepingIds.stream().anyMatch(id -> Arrays.equals(hash.getDigest(), id))); splits.forEach(s -> assertTrue(allKeepingIds.stream().anyMatch(id -> Arrays.equals(s.getId().getDigest(), id)))); result = client.getContract(origin, 10); List<byte[]> keepingIds = result.getListOrThrow("contractIds"); assertFalse(result.containsKey("packedContract")); assertEquals(keepingIds.size(), 10); assertTrue(keepingIds.stream().anyMatch(id -> Arrays.equals(hash.getDigest(), id))); for (int i = splits.size() - 1; i > splits.size() - 10; i--) { final HashId hashSplit = splits.get(i).getId(); assertTrue(keepingIds.stream().anyMatch(id -> Arrays.equals(hashSplit.getDigest(), id))); } mm.forEach(x -> x.config.setQueryContractsLimit(20)); result = client.getContract(origin); keepingIds = result.getListOrThrow("contractIds"); assertFalse(result.containsKey("packedContract")); assertEquals(keepingIds.size(), 20); assertTrue(keepingIds.stream().anyMatch(id -> Arrays.equals(hash.getDigest(), id))); for (int i = splits.size() - 1; i > splits.size() - 20; i--) { final HashId hashSplit = splits.get(i).getId(); assertTrue(keepingIds.stream().anyMatch(id -> Arrays.equals(hashSplit.getDigest(), id))); } result = client.getContract(origin, 30); keepingIds = result.getListOrThrow("contractIds"); assertFalse(result.containsKey("packedContract")); assertEquals(keepingIds.size(), 20); assertTrue(keepingIds.stream().anyMatch(id -> Arrays.equals(hash.getDigest(), id))); for (int i = splits.size() - 1; i > splits.size() - 20; i--) { final HashId hashSplit = splits.get(i).getId(); assertTrue(keepingIds.stream().anyMatch(id -> Arrays.equals(hashSplit.getDigest(), id))); } mm.forEach(x -> x.shutdown()); }
@Test public void joinFromDifferentOwners() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true)); Thread.sleep(2000); PrivateKey issuer = TestKeys.privateKey(11); PrivateKey owner1 = TestKeys.privateKey(12); PrivateKey owner2 = TestKeys.privateKey(13); PrivateKey owner3 = TestKeys.privateKey(14); Contract token = ContractsService.createTokenContract(new HashSet<>(Do.listOf(issuer)), new HashSet<>(Do.listOf(owner1.getPublicKey())), new BigDecimal("3000")); assertEquals(ts.client.register(token.getPackedTransaction(), 15000).state, ItemState.APPROVED); Contract part1 = token.createRevision(owner1); Contract[] parts = part1.split(2); Contract part2 = parts[0]; Contract part3 = parts[1]; part1.setOwnerKey(owner1.getPublicKey()); part1.getStateData().set("amount", "1000"); part2.setOwnerKey(owner2.getPublicKey()); part2.getStateData().set("amount", "1000"); part3.setOwnerKey(owner3.getPublicKey()); part3.getStateData().set("amount", "1000"); part2.seal(); part3.seal(); part1.seal(); ItemResult rr = ts.client.register(part1.getPackedTransaction(), 15000); System.out.println(rr.errors); assertEquals(rr.state, ItemState.APPROVED); assertEquals(ts.client.getState(part2.getId()).state, ItemState.APPROVED); assertEquals(ts.client.getState(part3.getId()).state, ItemState.APPROVED); part1 = Contract.fromPackedTransaction(part1.getPackedTransaction()); part2 = Contract.fromPackedTransaction(part2.getPackedTransaction()); part3 = Contract.fromPackedTransaction(part3.getPackedTransaction()); Contract badJoin = part1.createRevision(owner1); badJoin.addRevokingItems(part2); badJoin.addRevokingItems(part3); badJoin.getStateData().set("amount", "3000"); badJoin.seal(); badJoin.check(); assertEquals(ts.client.register(badJoin.getPackedTransaction(), 15000).state, ItemState.DECLINED); Contract goodJoin = part1.createRevision(owner1, owner2, owner3); goodJoin.addRevokingItems(part2); goodJoin.addRevokingItems(part3); goodJoin.getStateData().set("amount", "3000"); goodJoin.seal(); assertEquals(ts.client.register(goodJoin.getPackedTransaction(), 15000).state, ItemState.APPROVED); ts.nodes.forEach(m -> m.shutdown()); }
@Test public void splitJoinCaseTest() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Set<PrivateKey> issuersPriv = new HashSet<>(); Set<PublicKey> ownersPub = new HashSet<>(); Set<PrivateKey> ownersPriv = new HashSet<>(); issuersPriv.add(TestKeys.privateKey(1)); ownersPub.add(TestKeys.publicKey(2)); ownersPriv.add(TestKeys.privateKey(2)); Contract token = ContractsService.createTokenContract(issuersPriv, ownersPub, new BigDecimal("10000")); assertTrue(token.check()); assertEquals(ts.client.register(token.getPackedTransaction(), 15000).state, ItemState.APPROVED); Contract token1 = ContractsService.createSplit(token, new BigDecimal("5000"), "amount", ownersPriv, true); assertTrue(token1.check()); Contract token2 = (Contract) token1.getNewItems().iterator().next(); token1 = Contract.fromPackedTransaction(token1.getPackedTransaction()); token2 = Contract.fromPackedTransaction(token2.getPackedTransaction()); assertEquals(ts.client.register(token1.getPackedTransaction(), 15000).state, ItemState.APPROVED); assertEquals(ts.client.getState(token2.getId()).state, ItemState.APPROVED); List<Contract> contracts = ContractsService.createSplitJoin(Do.listOf(token1, token2), Do.listOf("6000", "1000", "500", "500"), Do.listOf(TestKeys.publicKey(4).getShortAddress(), TestKeys.publicKey(5).getShortAddress(), TestKeys.publicKey(6).getShortAddress(), TestKeys.publicKey(7).getShortAddress()), ownersPriv, "amount"); assertEquals(ts.client.register(contracts.get(0).getPackedTransaction(), 15000).state, ItemState.APPROVED); ts.shutdown(); }
@Test public void fakeParent() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Contract contract = new Contract(TestKeys.privateKey(1)); contract.seal(); assertEquals(ts.client.register(contract.getPackedTransaction(), 15000).state, ItemState.APPROVED); Contract contract2 = new Contract(TestKeys.privateKey(2)); contract2.addRevokingItems(contract); contract2.getState().setParent(contract.getId()); contract2.seal(); assertEquals(ts.client.register(contract2.getPackedTransaction(), 15000).state, ItemState.DECLINED); assertEquals(ts.client.getState(contract.getId()).state, ItemState.APPROVED); ts.shutdown(); }
@Test public void informerTest() throws Exception { TestSpace ts = prepareTestSpace(); Contract payment = getApprovedUContract(ts); Set<PrivateKey> paymentKeys = new HashSet(); paymentKeys.add(ts.myKey); Contract c = new Contract(TestKeys.privateKey(1)); Binder s = BossBiMapper.serialize(c); ZonedDateTime cr = ZonedDateTime.now().minusMonths(1); s.getBinder("definition").set("created_at", cr); s.getBinder("state").set("created_at", cr); c = BossBiMapper.deserialize(s); c.getKeysToSignWith().add(TestKeys.privateKey(1)); c.seal(); Parcel parcel = ContractsService.createParcel(c, payment, 1, paymentKeys); ItemResult res = ts.client.registerParcelWithState(parcel.pack(), 15000); assertSame(res.state, ItemState.UNDEFINED); assertEquals(1, res.errors.size()); System.out.println(res.errors); payment = parcel.getPayment().getContract(); c = new Contract(TestKeys.privateKey(1)); for (int i = 0; i < 20; i++) { c.addNewItems(new Contract(TestKeys.privateKey(1))); } c.seal(); parcel = ContractsService.createParcel(c, payment, 1, paymentKeys); res = ts.client.registerParcelWithState(parcel.pack(), 15000); assertSame(res.state, ItemState.UNDEFINED); assertEquals(1, res.errors.size()); System.out.println(res.errors); payment = parcel.getPayment().getContract(); c = new Contract(TestKeys.privateKey(1)); Contract ri = new Contract(TestKeys.privateKey(2)); ri.seal(); c.addRevokingItems(ri); c.seal(); parcel = ContractsService.createParcel(c, payment, 1, paymentKeys); res = ts.client.registerParcelWithState(parcel.pack(), 15000); assertTrue(res.state == ItemState.DECLINED); assertEquals(1, res.errors.size()); System.out.println(res.errors); payment = parcel.getPayment().getContract(); c = new Contract(TestKeys.privateKey(1)); c.seal(); parcel = ContractsService.createParcel(c, payment, 1, paymentKeys); res = ts.client.registerParcelWithState(parcel.pack(), 15000); assertSame(res.state, ItemState.APPROVED); payment = parcel.getPayment().getContract(); c = new Contract(TestKeys.privateKey(1)); c.seal(); parcel = ContractsService.createParcel(c, payment, -1, paymentKeys); res = ts.client.registerParcelWithState(parcel.pack(), 15000); ItemResult state = ts.client.getState(parcel.getPaymentContract().getId()); assertSame(state.state, ItemState.DECLINED); assertSame(res.state, ItemState.UNDEFINED); assertEquals(0, res.errors.size()); ts.shutdown(); }
@Test public void demo() throws Exception { PrivateKey person1 = TestKeys.privateKey(1); PrivateKey person2 = TestKeys.privateKey(2); PrivateKey bank = TestKeys.privateKey(3); Contract commissionAccRur = new Contract(bank); Contract commissionAccEur = new Contract(bank); commissionAccRur.getStateData().put(ACC_TYPE_FIELD, ACC_TYPE_BANK); commissionAccEur.getStateData().put(ACC_TYPE_FIELD, ACC_TYPE_BANK); commissionAccRur.getStateData().put(ACC_CURRENCY_FIELD, ACC_CURRENCY_RUR); commissionAccEur.getStateData().put(ACC_CURRENCY_FIELD, ACC_CURRENCY_EUR); commissionAccRur.getStateData().put(ACC_COMMISSION_PERCENT_FIELD, "0.0"); commissionAccEur.getStateData().put(ACC_COMMISSION_PERCENT_FIELD, "0.0"); commissionAccRur.getStateData().put(ACC_COMMISSION_ACCOUNT_FIELD, null); commissionAccEur.getStateData().put(ACC_COMMISSION_ACCOUNT_FIELD, null); commissionAccRur.seal(); commissionAccEur.seal(); Contract account1rur = new Contract(person1); Contract account2rur = new Contract(person2); Contract account2eur = new Contract(person2); account1rur.getStateData().put(ACC_TYPE_FIELD, ACC_TYPE_PERSONAL); account2rur.getStateData().put(ACC_TYPE_FIELD, ACC_TYPE_PERSONAL); account2eur.getStateData().put(ACC_TYPE_FIELD, ACC_TYPE_PERSONAL); account1rur.getStateData().put(ACC_CURRENCY_FIELD, ACC_CURRENCY_RUR); account2rur.getStateData().put(ACC_CURRENCY_FIELD, ACC_CURRENCY_RUR); account2eur.getStateData().put(ACC_CURRENCY_FIELD, ACC_CURRENCY_EUR); account1rur.getStateData().put(ACC_COMMISSION_PERCENT_FIELD, "0.1"); account2rur.getStateData().put(ACC_COMMISSION_PERCENT_FIELD, "0.0"); account2eur.getStateData().put(ACC_COMMISSION_PERCENT_FIELD, "0.2"); account1rur.getStateData().put(ACC_COMMISSION_ACCOUNT_FIELD, commissionAccRur.getId().toBase64String()); account2rur.getStateData().put(ACC_COMMISSION_ACCOUNT_FIELD, commissionAccRur.getId().toBase64String()); account2eur.getStateData().put(ACC_COMMISSION_ACCOUNT_FIELD, commissionAccEur.getId().toBase64String()); account1rur.seal(); account2rur.seal(); account2eur.seal(); Contract rurToken = new Contract(bank); SimpleRole tokenOwner = new SimpleRole("owner"); tokenOwner.addRequiredReference("canplayaccowner", Role.RequiredMode.ALL_OF); rurToken.registerRole(tokenOwner); rurToken.getStateData().put("account", account1rur.getId().toBase64String()); rurToken.getStateData().put(TOKEN_VALUE_FIELD, "100000"); RoleLink rl = new RoleLink("@owner", "owner"); rurToken.registerRole(rl); SplitJoinPermission sjp = new SplitJoinPermission(rl, Binder.of("field_name", TOKEN_VALUE_FIELD, "join_match_fields", Do.listOf("state.origin", TOKEN_ACCOUNT_PATH))); rurToken.addPermission(sjp); ModifyDataPermission mdp = new ModifyDataPermission(rl, Binder.of("fields", Binder.of(TOKEN_ACCOUNT_FIELD, null))); rurToken.addPermission(mdp); Reference canplayaccowner = new Reference(rurToken); canplayaccowner.name = "canplayaccowner"; List<String> conditions = new ArrayList<>(); conditions.add("ref.id==this." + TOKEN_ACCOUNT_PATH); conditions.add("this can_play ref.owner"); canplayaccowner.setConditions(Binder.of("all_of", conditions)); rurToken.addReference(canplayaccowner); Reference refAccount = new Reference(rurToken); refAccount.name = "refAccount"; refAccount.setConditions(Binder.of("all_of", Do.listOf("this." + TOKEN_ACCOUNT_PATH + " == ref.id"))); rurToken.addReference(refAccount); Reference refParent = new Reference(rurToken); refParent.name = "refParent"; refParent.setConditions(Binder.of("any_of", Do.listOf( "this.state.parent == ref.id", "this.state.parent undefined" ))); rurToken.addReference(refParent); Reference refParentAccount = new Reference(rurToken); refParentAccount.name = "refParentAccount"; refParentAccount.setConditions(Binder.of("any_of", Do.listOf( "refParent." + TOKEN_ACCOUNT_PATH + " == ref.id", "this.state.parent undefined" ))); rurToken.addReference(refParentAccount); Reference transferCheck = new Reference(rurToken); transferCheck.name = "transferCheck"; transferCheck.setConditions(Binder.of("any_of", Do.listOf( "this.state.parent undefined", "refParent." + TOKEN_ACCOUNT_PATH + " == this." + TOKEN_ACCOUNT_PATH, Binder.of("all_of", Do.listOf( "refAccount." + ACC_CURRENCY_PATH + " == refParentAccount." + ACC_CURRENCY_PATH, Binder.of("any_of", Do.listOf( Binder.of("all_of", Do.listOf( "this." + TOKEN_ACCOUNT_PATH + "==refParentAccount." + ACC_COMMISSION_ACCOUNT_PATH )), Binder.of("all_of", Do.listOf( "refParentAccount." + ACC_COMMISSION_PERCENT_PATH + "::number==0.0" )), Binder.of("all_of", Do.listOf( "ref." + TOKEN_VALUE_PATH + "::number == this." + TOKEN_VALUE_PATH + "::number * refParentAccount." + ACC_COMMISSION_PERCENT_PATH + "::number", "ref." + TOKEN_ACCOUNT_PATH + " == refParentAccount." + ACC_COMMISSION_ACCOUNT_PATH, "ref.transactional.data.transfer_id == this.id" )) )) )) ))); rurToken.addReference(transferCheck); rurToken.seal(); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), "_permanet", false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); main.config.getKeysWhiteList().add(TestKeys.publicKey(20)); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); assertTrue(main.config.isPermanetMode()); for (int i = 1; i < 4; i++) assertTrue(mm.get(i).config.isPermanetMode()); assertEquals(client.register(commissionAccEur.getPackedTransaction(), 8000).state, ItemState.APPROVED); assertEquals(client.register(commissionAccRur.getPackedTransaction(), 8000).state, ItemState.APPROVED); assertEquals(client.register(account1rur.getPackedTransaction(), 8000).state, ItemState.APPROVED); assertEquals(client.register(account2rur.getPackedTransaction(), 8000).state, ItemState.APPROVED); assertEquals(client.register(account2eur.getPackedTransaction(), 8000).state, ItemState.APPROVED); rurToken.getTransactionPack().addReferencedItem(account1rur); ItemResult ir = client.register(rurToken.getPackedTransaction(), 8000); System.out.println(ir.errors); assertEquals(ir.state, ItemState.APPROVED); Contract[] result = makeTransfer(rurToken, new BigDecimal("5000"), account1rur, account2rur, commissionAccRur, new HashSet<>(Do.listOf(person1)), client); assertNotNull(result[2]); result = makeTransfer(result[1], new BigDecimal("2000"), account2rur, account1rur, commissionAccRur, new HashSet<>(Do.listOf(person2)), client); assertNull(result[2]); mm.forEach(m->m.shutdown()); }
@Test public void multipleRevisions() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Contract c1 = new Contract(TestKeys.privateKey(1)); c1.seal(); ts.client.register(c1.getPackedTransaction(),8000); ts.clients.forEach(cl -> { try { assertEquals(cl.getState(c1.getId()).state, ItemState.APPROVED); } catch (ClientError clientError) { clientError.printStackTrace(); assertTrue(false); } }); Contract c2 = c1.createRevision(TestKeys.privateKey(1)); c2.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); c2.getKeysToSignWith().clear(); c2.seal(); Contract c3 = c2.createRevision(TestKeys.privateKey(2)); c3.setOwnerKeys(TestKeys.privateKey(3).getPublicKey()); c3.getKeysToSignWith().clear(); c3.seal(); Contract batch = ContractsService.createBatch(Do.listOf(TestKeys.privateKey(1), TestKeys.privateKey(2), TestKeys.privateKey(3)), c2,c3); ItemResult ir = ts.client.register(batch.getPackedTransaction(), 8000); System.out.println(ir.errors); assertEquals(ir.state,ItemState.APPROVED); ts.clients.forEach(cl -> { try { assertEquals(cl.getState(c2.getId()).state, ItemState.REVOKED); assertEquals(cl.getState(c3.getId()).state, ItemState.APPROVED); } catch (ClientError clientError) { clientError.printStackTrace(); assertTrue(false); } }); ts.shutdown(); }
@Test public void multipleRevisionsRollback() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Contract c1 = new Contract(TestKeys.privateKey(1)); c1.seal(); ts.client.register(c1.getPackedTransaction(),8000); ts.clients.forEach(cl -> { try { assertEquals(cl.getState(c1.getId()).state, ItemState.APPROVED); } catch (ClientError clientError) { clientError.printStackTrace(); assertTrue(false); } }); Contract c2 = c1.createRevision(TestKeys.privateKey(1)); c2.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); c2.getKeysToSignWith().clear(); c2.seal(); Contract c3 = c2.createRevision(TestKeys.privateKey(2)); c3.setOwnerKeys(TestKeys.privateKey(3).getPublicKey()); c3.getKeysToSignWith().clear(); c3.seal(); Contract unregistered = new Contract(TestKeys.privateKey(10)); RoleLink rl = new RoleLink("@revoke", "owner"); unregistered.registerRole(rl); unregistered.addPermission(new RevokePermission(rl)); unregistered.getSealedByKeys().clear(); unregistered.seal(); System.out.println("=============================================="); Contract revokesUnregistered = new Contract(TestKeys.privateKey(10)); revokesUnregistered.addRevokingItems(unregistered); revokesUnregistered.seal(); ts.nodes.get(0).node.getLedger().findOrCreate(unregistered.getId()).setState(ItemState.APPROVED).save(); ts.nodes.get(1).node.getLedger().findOrCreate(unregistered.getId()).setState(ItemState.REVOKED).save(); Contract batch = ContractsService.createBatch(Do.listOf(TestKeys.privateKey(1), TestKeys.privateKey(2), TestKeys.privateKey(3)), c2,c3,revokesUnregistered); ItemResult ir = ts.client.register(batch.getPackedTransaction(), 8000); System.out.println(ir.errors); assertEquals(ir.state,ItemState.DECLINED); ts.clients.forEach(cl -> { try { assertEquals(cl.getState(c1.getId()).state, ItemState.APPROVED); assertEquals(cl.getState(c2.getId()).state, ItemState.UNDEFINED); assertEquals(cl.getState(c3.getId()).state, ItemState.UNDEFINED); } catch (ClientError clientError) { clientError.printStackTrace(); assertTrue(false); } }); ts.shutdown(); }
@Test public void dupesTest() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Contract c = new Contract(TestKeys.privateKey(1)); c.seal(); assertEquals(ts.client.register(c.getPackedTransaction(),9000).state,ItemState.APPROVED); Contract c1 = c.createRevision(TestKeys.privateKey(1)); c1.setOwnerKeys(TestKeys.privateKey(2)); c1.getState().setBranchNumber(1); Contract c2 = c.createRevision(TestKeys.privateKey(1)); c2.setOwnerKeys(TestKeys.privateKey(2)); c2.getState().setBranchNumber(2); Contract batch = ContractsService.createBatch(Do.listOf(TestKeys.privateKey(1)),c1,c2); ItemResult ir = ts.client.register(batch.getPackedTransaction(), 9000); System.out.println(ir.errors); assertEquals(ir.state,ItemState.DECLINED); ts.shutdown(); }
@Test public void httpProxy() throws Exception { List<Main> nodes = new ArrayList<>(); for (int i = 0; i < 4; i++) nodes.add(createMain("node" + (i + 1), false)); nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey myKey = TestKeys.privateKey(3); ArrayList<Client> clientProxyToNode = new ArrayList<>(); for (int i = 0; i < 4; ++i) { Client clientProxyTo_i = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),myKey); clientProxyTo_i.startProxyToNode(i, null); clientProxyToNode.add(clientProxyTo_i); } HashId testHashId = HashId.createRandom(); nodes.get(0).node.getLedger().findOrCreate(testHashId).setState(ItemState.APPROVED).save(); nodes.get(1).node.getLedger().findOrCreate(testHashId).setState(ItemState.DECLINED).save(); nodes.get(2).node.getLedger().findOrCreate(testHashId).setState(ItemState.REVOKED).save(); nodes.get(3).node.getLedger().findOrCreate(testHashId).setState(ItemState.DISCARDED).save(); System.out.println("\n\n-------------------"); ItemResult answer = clientProxyToNode.get(0).getState(testHashId); System.out.println(answer); assertEquals(ItemState.APPROVED, answer.state); answer = clientProxyToNode.get(1).getState(testHashId); System.out.println(answer); assertEquals(ItemState.DECLINED, answer.state); answer = clientProxyToNode.get(2).getState(testHashId); System.out.println(answer); assertEquals(ItemState.REVOKED, answer.state); answer = clientProxyToNode.get(3).getState(testHashId); System.out.println(answer); assertEquals(ItemState.DISCARDED, answer.state); System.out.println("-------------------\n\n"); nodes.forEach(n->n.shutdown()); }
@Test public void httpProxyRecursion() throws Exception { List<Main> nodes = new ArrayList<>(); for (int i = 0; i < 4; i++) nodes.add(createMain("node" + (i + 1), false)); nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey myKey = TestKeys.privateKey(3); Client clientProxy = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),myKey); clientProxy.startProxyToNode(1, null); HashId testHashId = HashId.createRandom(); nodes.get(0).node.getLedger().findOrCreate(testHashId).setState(ItemState.APPROVED).save(); nodes.get(1).node.getLedger().findOrCreate(testHashId).setState(ItemState.DECLINED).save(); nodes.get(2).node.getLedger().findOrCreate(testHashId).setState(ItemState.REVOKED).save(); nodes.get(3).node.getLedger().findOrCreate(testHashId).setState(ItemState.DISCARDED).save(); System.out.println("\n\n-------------------"); Client targetClient = clientProxy.getClient(2); BasicHttpClientSession targetSession = targetClient.getSession(); Binder cmd = Binder.of("command", "getState", "params", Binder.of("itemId", testHashId)); Binder commandParams = Binder.of("session_id", targetSession.getSessionId(), "params", targetSession.getSessionKey().etaEncrypt(Boss.pack(cmd))); Binder answer = clientProxy.command("proxy", "url", targetClient.getUrl(), "command", "proxyCommand", "params", commandParams); String answerError = answer.getStringOrThrow("error"); System.out.println("try recursion v1... answerError: " + answerError); assertEquals("COMMAND_FAILED [proxy] Unable to proxy command 'proxy'", answerError); System.out.println("-------------------\n\n"); nodes.forEach(n->n.shutdown()); }
@Test public void httpProxyRecursion2() throws Exception { List<Main> nodes = new ArrayList<>(); for (int i = 0; i < 4; i++) nodes.add(createMain("node" + (i + 1), false)); nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey myKey = TestKeys.privateKey(3); Client clientProxy = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),myKey); HashId testHashId = HashId.createRandom(); nodes.get(0).node.getLedger().findOrCreate(testHashId).setState(ItemState.APPROVED).save(); nodes.get(1).node.getLedger().findOrCreate(testHashId).setState(ItemState.DECLINED).save(); nodes.get(2).node.getLedger().findOrCreate(testHashId).setState(ItemState.REVOKED).save(); nodes.get(3).node.getLedger().findOrCreate(testHashId).setState(ItemState.DISCARDED).save(); System.out.println("\n\n-------------------"); Client targetClient1 = clientProxy.getClient(1); Client targetClient2 = clientProxy.getClient(2); BasicHttpClientSession targetSession1 = targetClient1.getSession(); BasicHttpClientSession targetSession2 = targetClient2.getSession(); Binder cmd2 = Binder.of("command", "getState", "params", Binder.of("itemId", testHashId)); Binder command2Params = Binder.of("session_id", targetSession2.getSessionId(), "params", targetSession2.getSessionKey().etaEncrypt(Boss.pack(cmd2))); Binder answer = clientProxy.command("proxy", "url", targetClient2.getUrl(), "command", "command", "params", command2Params); Binder answerBinder = Boss.load(answer.getBinaryOrThrow("result")); String answerError = answerBinder.getBinderOrThrow("response").getStringOrThrow("response"); System.out.println("try recursion v2... answerError: " + answerError); assertEquals("Access denied. Command 'command' is not allowed with 'proxy', use 'proxyCommand' instead.", answerError); System.out.println("-------------------\n\n"); nodes.forEach(n->n.shutdown()); }
@Test public void networkStatusTest() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n-> { try { n.config.getAddressesWhiteList().add(TestKeys.publicKey(1).getLongAddress()); } catch (EncryptionError encryptionError) { encryptionError.printStackTrace(); } }); Client client = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),TestKeys.privateKey(1)); HashId id1 = HashId.createRandom(); ts.nodes.forEach(n->n.node.getLedger().findOrCreate(id1).setState(ItemState.APPROVED).save()); assertTrue(client.isApprovedByNetwork(id1,0.9,3000)); HashId id2 = HashId.createRandom(); for(int i = 0; i < ts.nodes.size();i++) { ts.nodes.get(i).node.getLedger().findOrCreate(id2).setState(i==0?ItemState.DECLINED:ItemState.APPROVED); } for(int i = 0; i < 10;i++) { assertFalse(client.isApprovedByNetwork(id2, 0.8, 3000)); } ts.shutdown(); try { client.isApprovedByNetwork(HashId.createRandom(),0.1,3000); } catch (ClientError e) { System.out.println(e.getErrorRecord()); assertEquals(e.getErrorRecord().getError(), Errors.COMMAND_PENDING); } }
@Test public void pingTest() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n-> { try { n.config.getAddressesWhiteList().add(TestKeys.publicKey(1).getLongAddress()); } catch (EncryptionError encryptionError) { encryptionError.printStackTrace(); } }); Client client1 = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),TestKeys.privateKey(10)); try { Binder resErr = client1.getClient(0).pingNode(3,10000); fail(); } catch (Exception e) { System.out.println(e.getMessage()); } Client client = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),TestKeys.privateKey(1)); try { Binder resErr = client.getClient(0).pingNode(33,10000); fail(); } catch (Exception e) { System.out.println(e.getMessage()); } for(int i = 0; i < client.size();i++) { for(int j = 0; j < client.size();j++) { if(j == i) continue; Binder res = client.getClient(i).pingNode(j + 1, 10000); System.out.println(i+"->"+j+" " +res); assertTrue(res.getIntOrThrow("UDP") >= 0); assertTrue(res.getIntOrThrow("UDP") < 10); assertTrue(res.getIntOrThrow("TCP") >= 0); assertTrue(res.getIntOrThrow("TCP") < 15); } } ts.nodes.remove(ts.nodes.size()-1).shutdown(); for(int i = 0; i < client.size()-1;i++) { for(int j = 0; j < client.size();j++) { if(j == i) continue; Binder res = client.getClient(i).pingNode(j + 1, 500); if(j < client.size()-1) { assertTrue(res.getIntOrThrow("UDP") >= 0); assertTrue(res.getIntOrThrow("UDP") < 10); assertTrue(res.getIntOrThrow("TCP") >= 0); assertTrue(res.getIntOrThrow("TCP") < 10); } else { assertEquals(res.getIntOrThrow("UDP"),-1); assertEquals(res.getIntOrThrow("TCP"),-1); } } } ts.shutdown(); }
@Test public void secureLoanTestDefault() throws Exception{ TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey lenderKey = TestKeys.privateKey(1); PrivateKey borrowerKey = TestKeys.privateKey(2); KeyAddress lenderAddress = lenderKey.getPublicKey().getLongAddress(); KeyAddress borrowerAddress = borrowerKey.getPublicKey().getLongAddress(); Contract token = ContractsService.createTokenContract(new HashSet<>(Do.listOf(TestKeys.privateKey(15))),new HashSet<>(Do.listOf(lenderKey.getPublicKey())),new BigDecimal("1000")); token.seal(); assertEquals(ts.client.register(token.getPackedTransaction(),8000).state,ItemState.APPROVED); token = ContractsService.createSplit(token,new BigDecimal("200"),"amount",new HashSet<>(Do.listOf(lenderKey))); token.setCreatorKeys(lenderKey.getPublicKey()); Contract rest = (Contract) token.getNewItems().iterator().next(); rest.setCreatorKeys(lenderKey.getPublicKey()); rest.setOwnerKeys(borrowerAddress); rest.seal(); token.seal(); ItemResult ir = ts.client.register(token.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); Contract collateral = new Contract(TestKeys.privateKey(15)); collateral.setOwnerKeys(borrowerKey); collateral.getStateData().put("description","This is very valuable contract"); collateral.seal(); assertEquals(ts.client.register(collateral.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract[] res = SecureLoanHelper.initSecureLoan(null,lenderAddress, borrowerAddress, token, Duration.ofSeconds(3), collateral, "1000",false,token.getOrigin(),null,null); Contract secureLoan = res[0]; secureLoan.addSignatureToSeal(borrowerKey); secureLoan.addSignatureToSeal(lenderKey); ir = ts.client.register(secureLoan.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); Contract col1 = collateral.createRevision(borrowerKey,lenderKey); col1.setOwnerKeys(TestKeys.publicKey(4)); col1.seal(); col1.getTransactionPack().addReferencedItem(secureLoan); ir = ts.client.register(col1.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.DECLINED); Contract defaultAttempt = SecureLoanHelper.defaultSecureLoan(secureLoan)[0]; defaultAttempt.addSignatureToSeal(lenderKey); ir = ts.client.register(defaultAttempt.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.DECLINED); Thread.sleep(6000); res = SecureLoanHelper.defaultSecureLoan(secureLoan); secureLoan = res[0]; collateral = res[1]; secureLoan.addSignatureToSeal(lenderKey); ir = ts.client.register(secureLoan.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); Contract col2 = collateral.createRevision(lenderKey); col2.setOwnerKeys(TestKeys.publicKey(4)); col2.seal(); col2 = Contract.fromPackedTransaction(col2.getPackedTransaction()); assertTrue(col2.check()); ir = ts.client.register(col2.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); ts.shutdown(); }
@Test public void secureLoanTestRepayment() throws Exception{ TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey lenderKey = TestKeys.privateKey(1); PrivateKey borrowerKey = TestKeys.privateKey(2); KeyAddress lenderAddress = lenderKey.getPublicKey().getLongAddress(); KeyAddress borrowerAddress = borrowerKey.getPublicKey().getLongAddress(); Contract token = ContractsService.createTokenContract(new HashSet<>(Do.listOf(TestKeys.privateKey(15))),new HashSet<>(Do.listOf(lenderKey.getPublicKey())),"1000"); token.seal(); assertEquals(ts.client.register(token.getPackedTransaction(),8000).state,ItemState.APPROVED); token = ContractsService.createSplit(token,new BigDecimal("200"),"amount",new HashSet<>(Do.listOf(lenderKey))); token.setCreatorKeys(lenderAddress); Contract rest = (Contract) token.getNewItems().iterator().next(); rest.setCreatorKeys(lenderAddress); rest.setOwnerKeys(borrowerAddress); rest.seal(); token.seal(); assertEquals(ts.client.register(token.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract collateral = new Contract(borrowerKey); collateral.getStateData().put("description","This is very valuable contract"); collateral.seal(); assertEquals(ts.client.register(collateral.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract[] res = SecureLoanHelper.initSecureLoan(Binder.of("description","bla bla bla"),lenderAddress, borrowerAddress, token, Duration.ofSeconds(30), collateral, "1000",false,token.getOrigin(),null,null); Contract secureLoan = res[0]; secureLoan.addSignatureToSeal(borrowerKey); secureLoan.addSignatureToSeal(lenderKey); ItemResult ir = ts.client.register(secureLoan.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); token = res[1]; token = token.createRevision(borrowerKey); token.addRevokingItems(rest); token.getStateData().set("amount","1000"); token.seal(); ir = ts.client.register(token.getPackedTransaction(),8000); System.out.println(ir); res = SecureLoanHelper.repaySecureLoan(secureLoan,token); secureLoan = res[0]; secureLoan.addSignatureToSeal(borrowerKey); ir = ts.client.register(secureLoan.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); Contract tokenAtempt = token.createRevision(lenderKey); tokenAtempt.setOwnerKeys(TestKeys.publicKey(5)); tokenAtempt.seal(); tokenAtempt.getTransactionPack().addReferencedItem(secureLoan); ir = ts.client.register(tokenAtempt.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.DECLINED); Contract collateralAtempt = collateral.createRevision(borrowerKey); collateralAtempt.setOwnerKeys(TestKeys.publicKey(5)); collateralAtempt.seal(); collateralAtempt.getTransactionPack().addReferencedItem(secureLoan); ir = ts.client.register(collateralAtempt.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.DECLINED); res = SecureLoanHelper.closeSecureLoan(secureLoan); secureLoan = res[0]; token = res[1]; collateral = res[2]; secureLoan.addSignatureToSeal(lenderKey); secureLoan.addSignatureToSeal(borrowerKey); ir = ts.client.register(secureLoan.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); tokenAtempt = token.createRevision(lenderKey); tokenAtempt.setOwnerKeys(TestKeys.publicKey(5)); tokenAtempt.seal(); ir = ts.client.register(tokenAtempt.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); collateralAtempt = collateral.createRevision(borrowerKey); collateralAtempt.setOwnerKeys(TestKeys.publicKey(5)); collateralAtempt.seal(); ir = ts.client.register(collateralAtempt.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); ts.shutdown(); }
@Test public void secureLoanTestDefaultMintableSimple() throws Exception{ TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey lenderKey = TestKeys.privateKey(1); PrivateKey borrowerKey = TestKeys.privateKey(2); KeyAddress lenderAddress = lenderKey.getPublicKey().getLongAddress(); KeyAddress borrowerAddress = borrowerKey.getPublicKey().getLongAddress(); Contract token = ContractsService.createMintableTokenContract(new HashSet<>(Do.listOf(TestKeys.privateKey(15))), new HashSet<>(Do.listOf(lenderKey.getPublicKey())), new BigDecimal("800"), new BigDecimal("0.1"), "uEUR", "UniEuro", "Coin description"); token.seal(); assertEquals(ts.client.register(token.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract collateral = new Contract(borrowerKey); collateral.getStateData().put("description","This is very valuable contract"); collateral.seal(); assertEquals(ts.client.register(collateral.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract[] res = SecureLoanHelper.initSecureLoan(new Binder(),lenderAddress, borrowerAddress, token, Duration.ofSeconds(3), collateral, "1000",true,null,token.getIssuer().getSimpleAddress(), (String) token.getDefinition().getData().get("currency")); Contract secureLoan = res[0]; Compound compound = new Compound(); compound.addContract("loan",secureLoan,null); compound.getCompoundContract().addSignatureToSeal(borrowerKey); compound.getCompoundContract().addSignatureToSeal(lenderKey); ItemResult ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); Thread.sleep(6000); res = SecureLoanHelper.defaultSecureLoan(secureLoan); secureLoan = res[0]; compound = new Compound(); compound.addContract("loan",secureLoan,null); compound.getCompoundContract().addSignatureToSeal(lenderKey); collateral = res[1]; ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); collateral = collateral.createRevision(lenderKey); collateral.setOwnerKeys(TestKeys.publicKey(5)); collateral.seal(); ir = ts.client.register(collateral.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); ts.shutdown(); }
@Test public void secureLoanTestRepaymentMintableSimple() throws Exception{ TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); PrivateKey lenderKey = TestKeys.privateKey(1); PrivateKey borrowerKey = TestKeys.privateKey(2); KeyAddress lenderAddress = lenderKey.getPublicKey().getLongAddress(); KeyAddress borrowerAddress = borrowerKey.getPublicKey().getLongAddress(); Contract token = ContractsService.createMintableTokenContract(new HashSet<>(Do.listOf(TestKeys.privateKey(15))), new HashSet<>(Do.listOf(lenderKey.getPublicKey())), new BigDecimal("800"), new BigDecimal("0.1"), "uEUR", "UniEuro", "Coin description"); token.seal(); assertEquals(ts.client.register(token.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract rest = ContractsService.createMintableTokenContract(new HashSet<>(Do.listOf(TestKeys.privateKey(15))), new HashSet<>(Do.listOf(borrowerKey.getPublicKey())), new BigDecimal("200"), new BigDecimal("0.1"), "uEUR", "UniEuro", "Coin description"); rest.seal(); assertEquals(ts.client.register(rest.getPackedTransaction(),8000).state,ItemState.APPROVED); Contract collateral = new Contract(borrowerKey); collateral.getStateData().put("description","This is very valuable contract"); collateral.seal(); assertEquals(ts.client.register(collateral.getPackedTransaction(),8000).state,ItemState.APPROVED); PrivateKey issuerKey = TestKeys.privateKey(13); Contract[] res = SecureLoanHelper.initSecureLoan(Do.listOf(issuerKey.getPublicKey().getLongAddress()),null, lenderAddress, borrowerAddress, token, Duration.ofSeconds(300), collateral, "1000",true,null,token.getIssuer().getSimpleAddress(), (String) token.getDefinition().getData().get("currency")); Contract secureLoan = res[0]; secureLoan.seal(); Compound compound = new Compound(); compound.addContract("loan",secureLoan,null); compound.getCompoundContract().addSignatureToSeal(borrowerKey); compound.getCompoundContract().addSignatureToSeal(lenderKey); compound.getCompoundContract().addSignatureToSeal(issuerKey); ItemResult ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); token = res[1]; token = token.createRevision(borrowerKey); token.addRevokingItems(rest); token.getStateData().set("amount","1000"); token.seal(); ir = ts.client.register(token.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = SecureLoanHelper.repaySecureLoan(secureLoan,token); secureLoan = res[0]; compound = new Compound(); compound.addContract("loan",secureLoan,null); compound.getCompoundContract().addSignatureToSeal(borrowerKey); ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = SecureLoanHelper.closeSecureLoan(secureLoan); secureLoan = res[0]; token = res[1]; collateral = res[2]; compound = new Compound(); compound.addContract("loan",secureLoan,null); compound.getCompoundContract().addSignatureToSeal(borrowerKey); compound.getCompoundContract().addSignatureToSeal(lenderKey); ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); token = token.createRevision(lenderKey); token.setOwnerKeys(TestKeys.publicKey(5)); token.seal(); ir = ts.client.register(token.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); token = collateral.createRevision(borrowerKey); token.setOwnerKeys(TestKeys.publicKey(5)); token.seal(); ir = ts.client.register(token.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); ts.shutdown(); }
@Test public void testMainTopology() throws Exception { TestSpace ts = prepareTestSpace(); Client c = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),TestKeys.privateKey(1)); System.out.println(c.getVersion()); ts.shutdown(); }
@Test public void testReferencesToPermissionsAndCustomRoles() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Client c = new Client("./src/test_node_config_v2/test_node_config_v2.json",System.getProperty("java.io.tmpdir"),ts.myKey); Contract contract = new Contract(TestKeys.privateKey(0)); Contract contract2 = new Contract(TestKeys.privateKey(0)); ChangeNumberPermission changeNumberPermission = new ChangeNumberPermission(new RoleLink("@owner", contract,"owner"), Binder.of( "field_name", "field1", "min_value", 33, "max_value", 34, "min_step", 1, "max_step", 1 ) ); ChangeNumberPermission changeNumberPermission2 = new ChangeNumberPermission(new RoleLink("@owner", contract2,"owner"), Binder.of( "field_name", "field1", "min_value", 33, "max_value", 34, "min_step", 1, "max_step", 1 ) ); changeNumberPermission.setId("changenumber"); changeNumberPermission2.setId("changenumber2"); contract.addRole(new RoleLink("link_to_issuer",contract,"issuer")); contract.addPermission(changeNumberPermission); contract2.addPermission(changeNumberPermission2); contract.seal(); Reference reference = new Reference(contract2); reference.name = "test1"; reference.setConditions(Binder.of("all_of", Do.listOf("ref.id==\""+contract.getId().toBase64String()+"\"","this.definition.permissions.changenumber2==ref.definition.permissions.changenumber"))); contract2.addReference(reference); contract2.addNewItems(contract); contract2.seal(); assertEquals(c.register(contract2.getPackedTransaction(),8000).state,ItemState.APPROVED); assertTrue(c.isApprovedByNetwork(contract2.getId(),0.9,8000)); ts.shutdown(); }
@Test public void escrowHelperTest() throws Exception { KeyAddress issuerAddress = TestKeys.publicKey(9).getShortAddress(); KeyAddress contractorAddress = TestKeys.publicKey(10).getShortAddress(); KeyAddress customerAddress = TestKeys.publicKey(11).getShortAddress(); KeyAddress arbitratorAddress = TestKeys.publicKey(12).getShortAddress(); KeyAddress storageServiceAddress = TestKeys.publicKey(13).getShortAddress(); PrivateKey issuerKey = TestKeys.privateKey(9); PrivateKey contractorKey = TestKeys.privateKey(10); PrivateKey customerKey = TestKeys.privateKey(11); PrivateKey arbitratorKey = TestKeys.privateKey(12); PrivateKey storageServiceKey = TestKeys.privateKey(13); TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->{n.config.setIsFreeRegistrationsAllowedFromYaml(true); n.config.getAddressesWhiteList().add(ts.client.getSession().getPrivateKey().getPublicKey().getLongAddress());}); Contract payment; Contract escrow; ItemResult ir; Contract[] res; payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),Binder.of("data","asdasd123"),Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofDays(500),payment)[0]; escrow.addSignatureToSeal(issuerKey); escrow.addSignatureToSeal(customerKey); ir = ts.client.register(escrow.getPackedTransaction(),8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = EscrowHelper.assignEscrow(escrow,contractorAddress,Binder.of("description","Assignment is done with additional info..."))[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = EscrowHelper.completeEscrow(escrow,Binder.of("description","Completion details"))[0]; Compound compound = new Compound(); compound.addContract("escrow",escrow,null); compound.getCompoundContract().addSignatureToSeal(contractorKey); compound.getCompoundContract().addSignatureToSeal(storageServiceKey); ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = compound.getContract("escrow"); res = EscrowHelper.closeByCustomer(escrow); escrow = res[0]; compound = new Compound(); compound.addContract("escrow",escrow,null); compound.getCompoundContract().addSignatureToSeal(customerKey); compound.getCompoundContract().addSignatureToSeal(storageServiceKey); ir = ts.client.register(compound.getCompoundContract().getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = compound.getContract("escrow"); res = EscrowHelper.obtainPaymentOnClosedEscrow(escrow); payment = res[0]; payment.addSignatureToSeal(contractorKey); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = payment.createRevision(contractorKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),null,Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofDays(500),payment)[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(issuerKey); assertEquals(ts.client.register(escrow.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.assignEscrow(escrow,contractorAddress,Binder.of("description","Assignment is done with additional info..."))[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = EscrowHelper.completeEscrow(escrow,Binder.of("description","Completion details"))[0]; escrow.addSignatureToSeal(contractorKey); escrow.addSignatureToSeal(storageServiceKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = EscrowHelper.closeByArbitration(escrow); escrow = res[0]; escrow.addSignatureToSeal(arbitratorKey); escrow.addSignatureToSeal(contractorKey); escrow.addSignatureToSeal(storageServiceKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = EscrowHelper.obtainPaymentOnClosedEscrow(escrow); payment = res[0]; payment.addSignatureToSeal(contractorKey); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = payment.createRevision(contractorKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),Binder.of("aaa","111"),Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofDays(500),payment)[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); escrow.addSignatureToSeal(issuerKey); assertEquals(ts.client.register(escrow.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.assignEscrow(escrow,contractorAddress,Binder.of("description","Assignment is done with additional info..."))[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = EscrowHelper.completeEscrow(escrow,Binder.of("description","Completion details"))[0]; escrow.addSignatureToSeal(contractorKey); escrow.addSignatureToSeal(storageServiceKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = EscrowHelper.cancelEscrow(escrow); escrow = res[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = res[1]; payment = payment.createRevision(customerKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),null,Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofDays(500),payment)[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(issuerKey); assertEquals(ts.client.register(escrow.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.assignEscrow(escrow,contractorAddress,Binder.of("description","Assignment is done with additional info..."))[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); escrow = EscrowHelper.completeEscrow(escrow,Binder.of("description","Completion details"))[0]; escrow.addSignatureToSeal(contractorKey); escrow.addSignatureToSeal(storageServiceKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = EscrowHelper.cancelEscrow(escrow); escrow = res[0]; escrow.addSignatureToSeal(arbitratorKey); escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(storageServiceKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = res[1]; payment = payment.createRevision(customerKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),null,Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofDays(500),payment)[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(issuerKey); assertEquals(ts.client.register(escrow.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.assignEscrow(escrow,contractorAddress,Binder.of("description","Assignment is done with additional info..."))[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); res = EscrowHelper.cancelEscrow(escrow); escrow = res[0]; escrow.addSignatureToSeal(contractorKey); escrow.addSignatureToSeal(customerKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = res[1]; payment = payment.createRevision(customerKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); payment.getTransactionPack().addReferencedItem(escrow); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),null,Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofSeconds(3),payment)[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(issuerKey); assertEquals(ts.client.register(escrow.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.assignEscrow(escrow,contractorAddress,Binder.of("description","Assignment is done with additional info..."))[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(contractorKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); Thread.sleep(3000); res = EscrowHelper.cancelEscrow(escrow); escrow = res[0]; escrow.addSignatureToSeal(customerKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = res[1]; payment = payment.createRevision(customerKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = new Contract(customerKey); payment.seal(); assertEquals(ts.client.register(payment.getPackedTransaction(),8000).state,ItemState.APPROVED); escrow = EscrowHelper.initEscrow(Do.listOf(issuerAddress),null,Binder.of("description","This is description the work to be done"),customerAddress,arbitratorAddress,storageServiceAddress,Duration.ofSeconds(30000),payment)[0]; escrow.addSignatureToSeal(customerKey); escrow.addSignatureToSeal(issuerKey); assertEquals(ts.client.register(escrow.getPackedTransaction(),8000).state,ItemState.APPROVED); res = EscrowHelper.cancelEscrow(escrow); escrow = res[0]; escrow.addSignatureToSeal(customerKey); ir = ts.client.register(escrow.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); payment = res[1]; payment = payment.createRevision(customerKey); payment.setOwnerKeys(TestKeys.publicKey(20)); payment.seal(); ir = ts.client.register(payment.getPackedTransaction(), 8000); System.out.println(ir); assertEquals(ir.state,ItemState.APPROVED); ts.shutdown(); }
@Test public void errorsFromParcel() throws Exception { TestSpace ts = prepareTestSpace(); ts.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Contract contract = new Contract(TestKeys.privateKey(1)); contract.setIssuerKeys(TestKeys.privateKey(1).getPublicKey().getLongAddress()); contract.setOwnerKeys(TestKeys.privateKey(1).getPublicKey().getLongAddress()); contract.seal(); assertEquals(ts.client.register(contract.getPackedTransaction(),8000).state,ItemState.APPROVED); contract = contract.createRevision(TestKeys.privateKey(2)); contract.setOwnerKeys(TestKeys.privateKey(2)); contract.seal(); contract.check(); Contract u = getApprovedUContract(ts); Parcel p = ContractsService.createParcel(contract,u,contract.getProcessedCostU(),ts.getUKeys()); ItemResult ir = ts.client.registerParcelWithState(p.pack(), 8000); assertEquals(ir.state,ItemState.DECLINED); assertEquals(ir.errors.size(),contract.getErrors().size()); ts.shutdown(); }
@Ignore @Test public void checkMemoryLeaks() throws Exception { List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: List<Ledger> ledgers = new ArrayList<>(); for (int it = 0; it < 100; it++) { if (it % 10 == 0) System.out.println("Iteration " + it); dbUrls.stream().forEach(url -> { try { clearLedger(url); PostgresLedger ledger = new PostgresLedger(url); ledgers.add(ledger); } catch (Exception e) { e.printStackTrace(); } }); TestSpace ts = prepareTestSpace(); ts.node.config.getAddressesWhiteList().add(new KeyAddress(TestKeys.publicKey(3), 0, true)); Contract testContract = new Contract(ts.myKey); testContract.seal(); assertTrue(testContract.isOk()); Parcel parcel = createParcelWithFreshU(ts.client, testContract, Do.listOf(ts.myKey)); ts.client.registerParcelWithState(parcel.pack(), 18000); Contract testContract2 = new Contract(ts.myKey); testContract2.seal(); assertTrue(testContract2.isOk()); ts.client.register(testContract2.getPackedTransaction(), 18000); ts.nodes.forEach(x -> x.shutdown()); ts.myKey = null; ts.nodes.clear(); ts.node = null; ts.nodes = null; ts.client = null; ts = null; ledgers.stream().forEach(ledger -> ledger.close()); ledgers.clear(); System.gc(); Thread.sleep(2000); } }
@Test public void networkReconfigurationTestSerial() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMain("node" + (i + 1), "_dynamic_test", false)); } for (Main m : mm) { m.shutdown(); } mm.clear(); List<String> dbUrls = new ArrayList<>(); Thread.sleep(1000); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: for (int i = 0; i < 4; i++) { mm.add(createMainFromDb(dbUrls.get(i), false)); } PrivateKey myKey = TestKeys.privateKey(3); Main main = mm.get(3); PrivateKey universaKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); Contract contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); int attempts = 3; Client client = new Client(universaKey, main.myInfo, null); ItemResult rr = client.register(contract.getPackedTransaction(), 5000); while (attempts-- > 0) { rr = client.getState(contract.getId()); System.out.println(rr); Thread.currentThread().sleep(1000); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.PENDING_POSITIVE); contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); Client clientKnown = new Client(universaKey, mm.get(0).myInfo, null); clientKnown.register(contract.getPackedTransaction(), 15000); while (true) { rr = clientKnown.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (int i = 0; i < 3; i++) { mm.get(i).node.addNode(main.myInfo); } contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); client.register(contract.getPackedTransaction(), 15000); while (true) { rr = client.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (int i = 0; i < 3; i++) { mm.get(i).node.removeNode(main.myInfo); } contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); attempts = 3; rr = client.register(contract.getPackedTransaction(), 15000); while (attempts-- > 0) { rr = client.getState(contract.getId()); Thread.currentThread().sleep(1000); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.PENDING_POSITIVE); contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); clientKnown.register(contract.getPackedTransaction(), 15000); while (true) { rr = clientKnown.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (Main m : mm) { m.shutdown(); } }
@Ignore @Test public void networkReconfigurationTestParallel() throws Exception { if(1 > 0) return; List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMain("node" + (i + 1), "_dynamic_test", false)); } for (Main m : mm) { m.shutdown(); } mm.clear(); List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: Random rand = new Random(); rand.setSeed(new Date().getTime()); final ArrayList<Integer> clientSleeps = new ArrayList<>(); final ArrayList<Integer> nodeSleeps = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMainFromDb(dbUrls.get(i), false)); nodeSleeps.add(rand.nextInt(100)); } PrivateKey myKey = TestKeys.privateKey(3); final ArrayList<Client> clients = new ArrayList<>(); final ArrayList<Integer> clientNodes = new ArrayList<>(); final ArrayList<Contract> contracts = new ArrayList<>(); final ArrayList<Parcel> parcels = new ArrayList<>(); final ArrayList<Boolean> contractsApproved = new ArrayList<>(); for (int i = 0; i < 40; i++) { Contract contract = new Contract(myKey); contract.seal(); assertTrue(contract.isOk()); contracts.add(contract); contractsApproved.add(false); NodeInfo info = mm.get(rand.nextInt(3)).myInfo; clientNodes.add(info.getNumber()); Client client = new Client(TestKeys.privateKey(i), info, null); clients.add(client); clientSleeps.add(rand.nextInt(100)); Parcel parcel = createParcelWithFreshU(client, contract, Do.listOf(myKey)); parcels.add(parcel); } Semaphore semaphore = new Semaphore(-39); final AtomicInteger atomicInteger = new AtomicInteger(40); for (int i = 0; i < 40; i++) { int finalI = i; Thread th = new Thread(() -> { try { Thread.sleep(clientSleeps.get(finalI)); Contract contract = contracts.get(finalI); Client client = clients.get(finalI); System.out.println("Register item " + contract.getId().toBase64String() + " @ node #" + clientNodes.get(finalI)); client.registerParcelWithState(parcels.get(finalI).pack(), 15000); ItemResult rr; while (true) { rr = client.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); semaphore.release(); atomicInteger.decrementAndGet(); contractsApproved.set(finalI, true); } catch (ClientError clientError) { clientError.printStackTrace(); fail(clientError.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } }); th.start(); } for (int i = 0; i < 3; i++) { int finalI = i; Thread th = new Thread(() -> { try { Thread.sleep(nodeSleeps.get(finalI)); } catch (InterruptedException e) { e.printStackTrace(); fail(e.getMessage()); } System.out.println("Adding new node @ node #" + (finalI + 1)); mm.get(finalI).node.addNode(mm.get(3).myInfo); System.out.println("Done new node @ node #" + (finalI + 1)); }); th.start(); } Thread.sleep(5000); if (!semaphore.tryAcquire(15, TimeUnit.SECONDS)) { for (int i = 0; i < contractsApproved.size(); i++) { if (!contractsApproved.get(i)) { System.out.println("Stuck item:" + contracts.get(i).getId().toBase64String()); } } System.out.print("Client sleeps: "); for (Integer s : clientSleeps) { System.out.print(s + ", "); } System.out.println(); System.out.print("Node sleeps: "); for (Integer s : nodeSleeps) { System.out.print(s + ", "); } System.out.println(); fail("Items stuck: " + atomicInteger.get()); } for (Main m : mm) { m.shutdown(); } System.gc(); }
@Ignore @Test public void reconfigurationContractTest() throws Exception { PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); List<Main> mm = new ArrayList<>(); List<PrivateKey> nodeKeys = new ArrayList<>(); List<PrivateKey> nodeKeysNew = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMain("node" + (i + 1), "_dynamic_test", false)); if (i < 3) nodeKeys.add(new PrivateKey(Do.read("./src/test_node_config_v2_dynamic_test/node" + (i + 1) + "/tmp/node2_" + (i + 1) + ".private.unikey"))); nodeKeysNew.add(new PrivateKey(Do.read("./src/test_node_config_v2_dynamic_test/node" + (i + 1) + "/tmp/node2_" + (i + 1) + ".private.unikey"))); } List<NodeInfo> netConfig = mm.get(0).netConfig.toList(); List<NodeInfo> netConfigNew = mm.get(3).netConfig.toList(); for (Main m : mm) { m.shutdown(); } mm.clear(); Contract configContract = createNetConfigContract(netConfig, issuerKey); List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: for (int i = 0; i < 4; i++) { mm.add(createMainFromDb(dbUrls.get(i), false)); } Client client = new Client(TestKeys.privateKey(0), mm.get(0).myInfo, null); Parcel parcel = createParcelWithFreshU(client, configContract, Do.listOf(issuerKey)); client.registerParcelWithState(parcel.pack(), 15000); ItemResult rr; while (true) { rr = client.getState(configContract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); configContract = createNetConfigContract(configContract, netConfigNew, nodeKeys); parcel = createParcelWithFreshU(client, configContract, nodeKeys); client.registerParcelWithState(parcel.pack(), 15000); while (true) { rr = client.getState(configContract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); Thread.sleep(1000); for (Main m : mm) { assertEquals(m.config.getPositiveConsensus(), 3); } configContract = createNetConfigContract(configContract, netConfig, nodeKeys); parcel = createParcelWithFreshU(client, configContract, nodeKeys); client.registerParcelWithState(parcel.pack(), 15000); while (true) { rr = client.getState(configContract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); Thread.sleep(1000); for (Main m : mm) { assertEquals(m.config.getPositiveConsensus(), 2); } for (Main m : mm) { m.shutdown(); } }
@Test public void checkShutdown() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Parcel parcel = createParcelWithFreshU(client, testContract, Do.listOf(myKey)); client.registerParcelWithState(parcel.pack(), 5000); System.out.println(">> before shutdown state: " + client.getState(parcel.getPayloadContract().getId())); System.out.println(">> before shutdown state: " + client.getState(parcel.getPayloadContract().getNew().get(0).getId())); main.shutdown(); Thread.sleep(8000); mm.remove(main); main = createMain("node1", false); mm.add(main); try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Thread.currentThread().sleep(8000); ItemResult itemResult = client.getState(parcel.getPayloadContract().getId()); ItemResult itemResult2 = client.getState(parcel.getPayloadContract().getNew().get(0).getId()); System.out.println(">> after shutdown state: " + itemResult + " and new " + itemResult2); while (itemResult.state.isPending()) { Thread.currentThread().sleep(500); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println(">> wait result: " + itemResult); } itemResult2 = client.getState(parcel.getPayloadContract().getNew().get(0).getId()); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(ItemState.APPROVED, itemResult2.state); mm.forEach(x -> x.shutdown()); }
@Test public void registerContractWithAnonymousId() throws Exception { TestSpace ts = prepareTestSpace(); PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); byte[] myAnonId = newPrivateKey.createAnonymousId(); Contract contract = new Contract(); contract.setExpiresAt(ZonedDateTime.now().plusDays(90)); Role r = contract.setIssuerKeys(AnonymousId.fromBytes(myAnonId)); contract.registerRole(new RoleLink("owner", "issuer")); contract.registerRole(new RoleLink("creator", "issuer")); contract.addPermission(new ChangeOwnerPermission(r)); contract.addSignerKey(newPrivateKey); contract.seal(); assertTrue(contract.isOk()); System.out.println("contract.check(): " + contract.check()); contract.traceErrors(); ts.client.getSession().setPrivateKey(newPrivateKey); ts.client.restart(); ItemResult itemResult = ts.client.register(contract.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); ts.nodes.forEach(x -> x.shutdown()); }
@Ignore @Test public void udpDisruptionTest() throws Exception { List<Main> mm = new ArrayList<>(); final int NODE_COUNT = 4; final int PORT_BASE = 12000; final int TEST_MODE = UDPAdapter.PacketTypes.HELLO; for (int i = 0; i < NODE_COUNT; i++) { mm.add(createMain("node" + (i + 1), false)); } class TestRunnable implements Runnable { int finalI; int finalJ; boolean alive = true; @Override public void run() { try { NodeInfo source = mm.get(finalI).myInfo; NodeInfo destination = mm.get(finalJ).myInfo; DatagramSocket socket = new DatagramSocket(PORT_BASE + finalI * NODE_COUNT + finalJ); while (alive) { if (TEST_MODE == UDPAdapter.PacketTypes.HELLO) sendHello(source, destination, mm.get(finalI).network.getUDPAdapter(), socket); else if (TEST_MODE == UDPAdapter.PacketTypes.WELCOME) sendWelcome(source, destination, mm.get(finalI).network.getUDPAdapter(), socket); else sendDataGarbage(source, destination, mm.get(finalI).network.getUDPAdapter(), socket); Thread.sleep(4); } } catch (Exception e) { System.out.println("runnable exception: " + e.toString()); } } } List<Thread> threadsList = new ArrayList<>(); List<TestRunnable> runnableList = new ArrayList<>(); for (int i = 0; i < NODE_COUNT; i++) { for (int j = 0; j < NODE_COUNT; j++) { if (j == i) continue; final int finalI = i; final int finalJ = j; TestRunnable runnableSingle = new TestRunnable(); runnableList.add(runnableSingle); threadsList.add( new Thread(() -> { runnableSingle.finalI = finalI; runnableSingle.finalJ = finalJ; runnableSingle.run(); })); } } for (Thread th : threadsList) { th.start(); } Thread.sleep(5000); PrivateKey myKey = TestKeys.privateKey(0); Client client = new Client(myKey, mm.get(0).myInfo, null); Contract contract = new Contract(myKey); contract.seal(); Parcel parcel = createParcelWithFreshU(client, contract, Do.listOf(myKey)); client.registerParcelWithState(parcel.pack(), 60000); ItemResult rr; while (true) { rr = client.getState(contract.getId()); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (TestRunnable tr : runnableList) { tr.alive = false; } for (Thread th : threadsList) { th.interrupt(); } mm.forEach(x -> x.shutdown()); }
@Ignore @Test public void dbSanitationTest() throws Exception { final int NODE_COUNT = 4; PrivateKey myKey = TestKeys.privateKey(NODE_COUNT); List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: List<Ledger> ledgers = new ArrayList<>(); dbUrls.stream().forEach(url -> { try { PostgresLedger ledger = new PostgresLedger(url); ledgers.add(ledger); } catch (Exception e) { e.printStackTrace(); } }); Random random = new Random(123); List<Contract> origins = new ArrayList<>(); List<Contract> newRevisions = new ArrayList<>(); List<Contract> newContracts = new ArrayList<>(); final int N = 100; for (int i = 0; i < N; i++) { Contract origin = new Contract(myKey); origin.seal(); origins.add(origin); Contract newRevision = origin.createRevision(myKey); if (i < N / 2) { newRevision.setOwnerKeys(TestKeys.privateKey(NODE_COUNT + 1).getPublicKey()); } else { } Contract newContract = new Contract(myKey); newRevision.addNewItems(newContract); newRevision.seal(); newContracts.add(newContract); newRevisions.add(newRevision); int unfinishedNodesCount = random.nextInt(2) + 1; Set<Integer> unfinishedNodesNumbers = new HashSet<>(); while (unfinishedNodesCount > unfinishedNodesNumbers.size()) { unfinishedNodesNumbers.add(random.nextInt(NODE_COUNT) + 1); } System.out.println("item# " + newRevision.getId().toBase64String().substring(0, 6) + " nodes " + unfinishedNodesNumbers.toString()); int finalI = i; for (int j = 0; j < NODE_COUNT; j++) { boolean finished = !unfinishedNodesNumbers.contains(j + 1); Ledger ledger = ledgers.get(j); StateRecord originRecord = ledger.findOrCreate(origin.getId()); originRecord.setExpiresAt(origin.getExpiresAt()); originRecord.setCreatedAt(origin.getCreatedAt()); StateRecord newRevisionRecord = ledger.findOrCreate(newRevision.getId()); newRevisionRecord.setExpiresAt(newRevision.getExpiresAt()); newRevisionRecord.setCreatedAt(newRevision.getCreatedAt()); StateRecord newContractRecord = ledger.findOrCreate(newContract.getId()); newContractRecord.setExpiresAt(newContract.getExpiresAt()); newContractRecord.setCreatedAt(newContract.getCreatedAt()); if (finished) { if (finalI < N / 2) { originRecord.setState(ItemState.REVOKED); newContractRecord.setState(ItemState.APPROVED); newRevisionRecord.setState(ItemState.APPROVED); } else { originRecord.setState(ItemState.APPROVED); newContractRecord.setState(ItemState.UNDEFINED); newRevisionRecord.setState(ItemState.DECLINED); } } else { originRecord.setState(ItemState.LOCKED); originRecord.setLockedByRecordId(newRevisionRecord.getRecordId()); newContractRecord.setState(ItemState.LOCKED_FOR_CREATION); newContractRecord.setLockedByRecordId(newRevisionRecord.getRecordId()); newRevisionRecord.setState(finalI < N / 2 ? ItemState.PENDING_POSITIVE : ItemState.PENDING_NEGATIVE); } originRecord.save(); ledger.putItem(originRecord, origin, Instant.now().plusSeconds(3600 * 24)); newRevisionRecord.save(); ledger.putItem(newRevisionRecord, newRevision, Instant.now().plusSeconds(3600 * 24)); if (newContractRecord.getState() == ItemState.UNDEFINED) { newContractRecord.destroy(); } else { newContractRecord.save(); } } } ledgers.stream().forEach(ledger -> ledger.close()); ledgers.clear(); List<Main> mm = new ArrayList<>(); List<Client> clients = new ArrayList<>(); for (int i = 0; i < NODE_COUNT; i++) { Main m = createMain("node" + (i + 1), false); m.config.setIsFreeRegistrationsAllowedFromYaml(true); mm.add(m); Client client = new Client(TestKeys.privateKey(i), m.myInfo, null); clients.add(client); } while (true) { try { for (int i = 0; i < NODE_COUNT; i++) { clients.get(i).getState(newRevisions.get(0)); } break; } catch (ClientError e) { Thread.sleep(1000); mm.stream().forEach(m -> System.out.println("node#" + m.myInfo.getNumber() + " is " + (m.node.isSanitating() ? "" : "not ") + "sanitating")); } } Contract contract = new Contract(TestKeys.privateKey(3)); contract.seal(); ItemResult ir = clients.get(0).register(contract.getPackedTransaction(), 10000); ir.errors.toString(); for (int i = 0; i < N; i++) { ItemResult rr = clients.get(i % NODE_COUNT).getState(newRevisions.get(i).getId()); ItemState targetState = i < N / 2 ? ItemState.APPROVED : ItemState.DECLINED; assertEquals(rr.state, targetState); } Thread.sleep(1000); mm.stream().forEach(m -> m.shutdown()); Thread.sleep(1000); dbUrls.stream().forEach(url -> { try { PostgresLedger ledger = new PostgresLedger(url); assertTrue(ledger.findUnfinished().isEmpty()); ledger.close(); } catch (Exception e) { e.printStackTrace(); } }); }
@Ignore @Test public void nodeStatsTest() throws Exception { PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); TestSpace testSpace = prepareTestSpace(issuerKey); Thread.sleep(2000); Binder b = testSpace.client.getStats(90); int uptime = b.getIntOrThrow("uptime"); testSpace.nodes.get(0).config.setStatsIntervalSmall(Duration.ofSeconds(4)); testSpace.nodes.get(0).config.setStatsIntervalBig(Duration.ofSeconds(60)); testSpace.nodes.get(0).config.getAddressesWhiteList().add(new KeyAddress(issuerKey.getPublicKey(), 0, true)); while (testSpace.client.getStats(null).getIntOrThrow("uptime") >= uptime) { Thread.sleep(500); } for (int i = 0; i < 30; i++) { Instant now = Instant.now(); Contract contract = new Contract(issuerKey); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); contract = new Contract(issuerKey); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); Thread.sleep(4000 - (Instant.now().toEpochMilli() - now.toEpochMilli())); Binder binder = testSpace.client.getStats(90); assertEquals(binder.getIntOrThrow("smallIntervalApproved"), 2); int target = i < 15 ? (i + 1) * 2 : 30; assertTrue(binder.getIntOrThrow("bigIntervalApproved") <= target && binder.getIntOrThrow("bigIntervalApproved") >= target - 2); } testSpace.nodes.forEach(x -> x.shutdown()); }
@Test public void resynItemTest() throws Exception { PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); TestSpace testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); int absentNode = testSpace.nodes.size() - 1; testSpace.nodes.get(absentNode).shutdown(); testSpace.nodes.remove(absentNode); Contract contract = new Contract(issuerKey); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); Thread.sleep(2000); testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); StateRecord r0 = testSpace.nodes.get(0).node.getLedger().getRecord(contract.getId()); r0.setExpiresAt(r0.getExpiresAt().minusHours(1)); r0.save(); StateRecord r1 = testSpace.nodes.get(1).node.getLedger().getRecord(contract.getId()); r1.setCreatedAt(r1.getCreatedAt().plusHours(1)); r1.save(); Client absentNodeClient = new Client(testSpace.myKey, testSpace.nodes.get(absentNode).myInfo, null); assertEquals(absentNodeClient.getState(contract.getId()).state, ItemState.UNDEFINED); absentNodeClient.resyncItem(contract.getId()); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); ItemResult rr; while (true) { rr = absentNodeClient.getState(contract.getId()); if (!rr.state.isPending()) break; Thread.sleep(500); } assertEquals(rr.state, ItemState.APPROVED); Average createdAverage = new Average(); Average expiredAverage = new Average(); ItemResult ir0 = testSpace.nodes.get(0).node.checkItem(contract.getId()); ItemResult ir1 = testSpace.nodes.get(1).node.checkItem(contract.getId()); ItemResult ir2 = testSpace.nodes.get(2).node.checkItem(contract.getId()); createdAverage.update(ir0.createdAt.toEpochSecond()); createdAverage.update(ir2.createdAt.toEpochSecond()); expiredAverage.update(ir1.expiresAt.toEpochSecond()); expiredAverage.update(ir2.expiresAt.toEpochSecond()); assertEquals(rr.createdAt.toEpochSecond(), (long) createdAverage.average()); assertEquals(rr.expiresAt.toEpochSecond(), (long) expiredAverage.average()); testSpace.nodes.forEach(x -> x.shutdown()); }
@Test public void freeRegistrationsAllowedFromCoreVersion() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Contract contract = new Contract(TestKeys.privateKey(0)); contract.seal(); ItemState expectedState = ItemState.UNDEFINED; if (Core.VERSION.contains("private")) expectedState = ItemState.APPROVED; System.out.println("Core.VERSION: " + Core.VERSION); System.out.println("expectedState: " + expectedState); ItemResult itemResult = client.register(contract.getPackedTransaction(), 5000); System.out.println("itemResult: " + itemResult); assertEquals(expectedState, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void freeRegistrationsAllowedFromConfigOrVersion() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Contract contract = new Contract(TestKeys.privateKey(0)); contract.seal(); ItemState expectedState = ItemState.APPROVED; System.out.println("expectedState: " + expectedState); ItemResult itemResult = client.register(contract.getPackedTransaction(), 5000); System.out.println("itemResult: " + itemResult); assertEquals(expectedState, itemResult.state); main.config.setIsFreeRegistrationsAllowedFromYaml(false); contract = new Contract(TestKeys.privateKey(0)); contract.seal(); expectedState = ItemState.UNDEFINED; if (Core.VERSION.contains("private")) expectedState = ItemState.APPROVED; System.out.println("Core.VERSION: " + Core.VERSION); System.out.println("expectedState: " + expectedState); itemResult = client.register(contract.getPackedTransaction(), 5000); System.out.println("itemResult: " + itemResult); assertEquals(expectedState, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void testTokenContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract tokenContract = ContractsService.createTokenContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("1000000")); tokenContract.check(); tokenContract.traceErrors(); assertTrue(tokenContract.getOwner().isAllowedForKeys(ownerPublicKeys)); assertTrue(tokenContract.getIssuer().isAllowedForKeys(issuerPrivateKeys)); assertTrue(tokenContract.getCreator().isAllowedForKeys(issuerPrivateKeys)); assertFalse(tokenContract.getOwner().isAllowedForKeys(issuerPrivateKeys)); assertFalse(tokenContract.getIssuer().isAllowedForKeys(ownerPublicKeys)); assertFalse(tokenContract.getCreator().isAllowedForKeys(ownerPublicKeys)); assertTrue(tokenContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(tokenContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(tokenContract, "amount"), new Decimal(1000000)); assertEquals(tokenContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = tokenContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), "0.01"); assertEquals(splitJoinParams.get("min_unit"), "0.01"); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List) splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(tokenContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(tokenContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(tokenContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(tokenContract.isPermitted("change_owner", issuerPublicKeys)); assertTrue(tokenContract.isPermitted("split_join", ownerPublicKeys)); assertFalse(tokenContract.isPermitted("split_join", issuerPublicKeys)); ItemResult itemResult = client.register(tokenContract.getPackedTransaction(), 5000); System.out.println("token contract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void testMintableTokenContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract mintableTokenContract = ContractsService.createTokenContractWithEmission(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("300000000000")); mintableTokenContract.check(); mintableTokenContract.traceErrors(); ItemResult itemResult = client.register(mintableTokenContract.getPackedTransaction(), 5000); System.out.println("mintableTokenContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract emittedContract = ContractsService.createTokenEmission(mintableTokenContract, new BigDecimal("100000000000"), issuerPrivateKeys); emittedContract.check(); emittedContract.traceErrors(); assertEquals(emittedContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = emittedContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), "0.01"); assertEquals(splitJoinParams.get("min_unit"), "0.01"); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List) splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(emittedContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(emittedContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(emittedContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(emittedContract.isPermitted("change_owner", issuerPublicKeys)); assertTrue(emittedContract.isPermitted("split_join", ownerPublicKeys)); assertFalse(emittedContract.isPermitted("split_join", issuerPublicKeys)); itemResult = client.register(emittedContract.getPackedTransaction(), 5000); System.out.println("emittedContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(emittedContract.getStateData().getString("amount"), "400000000000"); assertEquals(ItemState.REVOKED, main.node.waitItem(mintableTokenContract.getId(), 8000).state); mm.forEach(x -> x.shutdown()); }
@Test public void testSplitAndJoinApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Set<PrivateKey> issuerPrivateKeys2 = new HashSet<>(asList(TestKeys.privateKey(2))); Contract contractC = ContractsService.createTokenContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("100")); contractC.check(); contractC.traceErrors(); ItemResult itemResult = client.register(contractC.getPackedTransaction(), 5000); System.out.println("contractC : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); Contract сontractA = ContractsService.createSplit(contractC, new BigDecimal("30"), "amount", issuerPrivateKeys2, true); Contract contractB = сontractA.getNew().get(0); assertEquals("70", сontractA.getStateData().get("amount").toString()); assertEquals("30", contractB.getStateData().get("amount").toString()); itemResult = client.register(сontractA.getPackedTransaction(), 5000); System.out.println("сontractA : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals("70", сontractA.getStateData().get("amount").toString()); assertEquals("30", contractB.getStateData().get("amount").toString()); assertEquals(ItemState.REVOKED, main.node.waitItem(contractC.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(сontractA.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(contractB.getId(), 5000).state); Contract contractC2 = ContractsService.createJoin(сontractA, contractB, "amount", issuerPrivateKeys2); contractC2.check(); contractC2.traceErrors(); assertTrue(contractC2.isOk()); itemResult = client.register(contractC2.getPackedTransaction(), 5000); System.out.println("contractC2 : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(new Decimal(100), contractC2.getStateData().get("amount")); assertEquals(ItemState.REVOKED, main.node.waitItem(contractC.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(сontractA.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(contractB.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(contractC2.getId(), 5000).state); mm.forEach(x -> x.shutdown()); }
@Test public void testShareContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract shareContract = ContractsService.createShareContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("100")); shareContract.check(); shareContract.traceErrors(); assertTrue(shareContract.getOwner().isAllowedForKeys(ownerPublicKeys)); assertTrue(shareContract.getIssuer().isAllowedForKeys(issuerPrivateKeys)); assertTrue(shareContract.getCreator().isAllowedForKeys(issuerPrivateKeys)); assertFalse(shareContract.getOwner().isAllowedForKeys(issuerPrivateKeys)); assertFalse(shareContract.getIssuer().isAllowedForKeys(ownerPublicKeys)); assertFalse(shareContract.getCreator().isAllowedForKeys(ownerPublicKeys)); assertTrue(shareContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(shareContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(shareContract, "amount"), new Decimal(100)); assertEquals(shareContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = shareContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), 1); assertEquals(splitJoinParams.get("min_unit"), 1); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List) splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(shareContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(shareContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(shareContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(shareContract.isPermitted("change_owner", issuerPublicKeys)); assertTrue(shareContract.isPermitted("split_join", ownerPublicKeys)); assertFalse(shareContract.isPermitted("split_join", issuerPublicKeys)); ItemResult itemResult = client.register(shareContract.getPackedTransaction(), 5000); System.out.println("shareContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void testNotaryContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> issuerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract notaryContract = ContractsService.createNotaryContract(issuerPrivateKeys, ownerPublicKeys); notaryContract.check(); notaryContract.traceErrors(); assertTrue(notaryContract.getOwner().isAllowedForKeys(ownerPublicKeys)); assertTrue(notaryContract.getIssuer().isAllowedForKeys(issuerPrivateKeys)); assertTrue(notaryContract.getCreator().isAllowedForKeys(issuerPrivateKeys)); assertFalse(notaryContract.getOwner().isAllowedForKeys(issuerPrivateKeys)); assertFalse(notaryContract.getIssuer().isAllowedForKeys(ownerPublicKeys)); assertFalse(notaryContract.getCreator().isAllowedForKeys(ownerPublicKeys)); assertTrue(notaryContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(notaryContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertTrue(notaryContract.isPermitted("revoke", ownerPublicKeys)); assertTrue(notaryContract.isPermitted("revoke", issuerPublicKeys)); assertTrue(notaryContract.isPermitted("change_owner", ownerPublicKeys)); assertFalse(notaryContract.isPermitted("change_owner", issuerPublicKeys)); ItemResult itemResult = client.register(notaryContract.getPackedTransaction(), 5000); System.out.println("notaryContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void testTwoSignedContractApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> martyPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PublicKey> stepaPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract baseContract = Contract.fromDslFile(ROOT_PATH + "DeLoreanOwnership.yml"); PrivateKey manufacturePrivateKey = new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey")); baseContract.addSignerKey(manufacturePrivateKey); baseContract.seal(); baseContract.check(); baseContract.traceErrors(); Contract twoSignContract = ContractsService.createTwoSignedContract(baseContract, martyPrivateKeys, stepaPublicKeys, false); twoSignContract = Contract.fromPackedTransaction(twoSignContract.getPackedTransaction()); twoSignContract.addSignatureToSeal(stepaPrivateKeys); twoSignContract.check(); twoSignContract.traceErrors(); ItemResult itemResult = client.register(twoSignContract.getPackedTransaction(), 5000); System.out.println("twoSignContract : " + itemResult); assertEquals(ItemState.DECLINED, itemResult.state); twoSignContract = Contract.fromPackedTransaction(twoSignContract.getPackedTransaction()); twoSignContract.addSignatureToSeal(martyPrivateKeys); twoSignContract.check(); twoSignContract.traceErrors(); System.out.println("Contract with two signature is valid: " + twoSignContract.isOk()); itemResult = client.register(twoSignContract.getPackedTransaction(), 5000); System.out.println("twoSignContract : " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void testRevocationContractsApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> issuerPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PublicKey> ownerPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract sourceContract = ContractsService.createShareContract(issuerPrivateKeys, ownerPublicKeys, new BigDecimal("100")); sourceContract.check(); sourceContract.traceErrors(); ItemResult itemResult = client.register(sourceContract.getPackedTransaction(), 5000); System.out.println("sourceContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(sourceContract.getId()).state); Contract revokeContract = ContractsService.createRevocation(sourceContract, TestKeys.privateKey(1)); revokeContract.check(); revokeContract.traceErrors(); itemResult = client.register(revokeContract.getPackedTransaction(), 5000); System.out.println("revokeContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(revokeContract.getId()).state); assertEquals(ItemState.REVOKED, client.getState(sourceContract.getId()).state); mm.forEach(x -> x.shutdown()); }
@Test public void testSwapContractsApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> martyPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PublicKey> martyPublicKeys = new HashSet<>(asList(TestKeys.publicKey(1))); Set<PublicKey> stepaPublicKeys = new HashSet<>(asList(TestKeys.publicKey(2))); Contract delorean = ContractsService.createTokenContract(martyPrivateKeys, martyPublicKeys, new BigDecimal("100"), new BigDecimal("0.0001")); delorean.seal(); delorean.check(); delorean.traceErrors(); ItemResult itemResult = client.register(delorean.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); Contract lamborghini = ContractsService.createTokenContract(stepaPrivateKeys, stepaPublicKeys, new BigDecimal("100"), new BigDecimal("0.0001")); lamborghini.seal(); lamborghini.check(); lamborghini.traceErrors(); itemResult = client.register(lamborghini.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); System.out.println("--- register swapped contracts using ContractsService ---"); Contract swapContract; swapContract = ContractsService.startSwap(delorean, lamborghini, martyPrivateKeys, stepaPublicKeys); swapContract = Contract.fromPackedTransaction(swapContract.getPackedTransaction()); ContractsService.signPresentedSwap(swapContract, stepaPrivateKeys); swapContract = Contract.fromPackedTransaction(swapContract.getPackedTransaction()); ContractsService.finishSwap(swapContract, martyPrivateKeys); swapContract.check(); swapContract.traceErrors(); System.out.println("Transaction contract for swapping is valid: " + swapContract.isOk()); itemResult = client.register(swapContract.getPackedTransaction(), 10000); assertEquals(ItemState.APPROVED, itemResult.state); System.out.println("--- check old revisions for ownership contracts ---"); ItemResult deloreanResult = main.node.waitItem(delorean.getId(), 5000); System.out.println("DeLorean revoked ownership contract revision " + delorean.getRevision() + " is " + deloreanResult + " by Network"); System.out.println("DeLorean revoked ownership was belongs to Marty: " + delorean.getOwner().isAllowedForKeys(martyPublicKeys)); assertEquals(ItemState.REVOKED, deloreanResult.state); ItemResult lamborghiniResult = main.node.waitItem(lamborghini.getId(), 5000); System.out.println("Lamborghini revoked ownership contract revision " + lamborghini.getRevision() + " is " + lamborghiniResult + " by Network"); System.out.println("Lamborghini revoked ownership was belongs to Stepa: " + lamborghini.getOwner().isAllowedForKeys(stepaPublicKeys)); assertEquals(ItemState.REVOKED, lamborghiniResult.state); System.out.println("--- check new revisions for ownership contracts ---"); Contract newDelorean = null; Contract newLamborghini = null; for (Contract c : swapContract.getNew()) { if (c.getParent().equals(delorean.getId())) { newDelorean = c; } if (c.getParent().equals(lamborghini.getId())) { newLamborghini = c; } } deloreanResult = main.node.waitItem(newDelorean.getId(), 5000); System.out.println("DeLorean ownership contract revision " + newDelorean.getRevision() + " is " + deloreanResult + " by Network"); System.out.println("DeLorean ownership is now belongs to Stepa: " + newDelorean.getOwner().isAllowedForKeys(stepaPublicKeys)); assertEquals(ItemState.APPROVED, deloreanResult.state); assertTrue(newDelorean.getOwner().isAllowedForKeys(stepaPublicKeys)); lamborghiniResult = main.node.waitItem(newLamborghini.getId(), 5000); System.out.println("Lamborghini ownership contract revision " + newLamborghini.getRevision() + " is " + lamborghiniResult + " by Network"); System.out.println("Lamborghini ownership is now belongs to Marty: " + newLamborghini.getOwner().isAllowedForKeys(martyPublicKeys)); assertEquals(ItemState.APPROVED, lamborghiniResult.state); assertTrue(newLamborghini.getOwner().isAllowedForKeys(martyPublicKeys)); mm.forEach(x -> x.shutdown()); }
@Test public void testSwapSplitJoin_Api2() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> user1PrivateKeySet = new HashSet<>(asList(TestKeys.privateKey(1))); Set<PrivateKey> user2PrivateKeySet = new HashSet<>(asList(TestKeys.privateKey(2))); Set<PublicKey> user1PublicKeySet = user1PrivateKeySet.stream().map(prv -> prv.getPublicKey()).collect(Collectors.toSet()); Set<PublicKey> user2PublicKeySet = user2PrivateKeySet.stream().map(prv -> prv.getPublicKey()).collect(Collectors.toSet()); Contract contractTOK92 = ContractsService.createTokenContract(user1PrivateKeySet, user1PublicKeySet, new BigDecimal("100"), new BigDecimal("0.0001")); Contract contractTOK93 = ContractsService.createTokenContract(user2PrivateKeySet, user2PublicKeySet, new BigDecimal("100"), new BigDecimal("0.001")); contractTOK92.seal(); contractTOK92.check(); contractTOK92.traceErrors(); ItemResult itemResult = client.register(contractTOK92.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); contractTOK93.seal(); contractTOK93.check(); contractTOK93.traceErrors(); itemResult = client.register(contractTOK93.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); System.out.println("--- tokens created ---"); Contract user1CoinsSplit = ContractsService.createSplit(contractTOK92, new BigDecimal("8.02"), "amount", user1PrivateKeySet); Contract user1CoinsSplitToUser2 = user1CoinsSplit.getNew().get(0); Contract user2CoinsSplit = ContractsService.createSplit(contractTOK93, new BigDecimal("10.01"), "amount", user2PrivateKeySet); Contract user2CoinsSplitToUser1 = user2CoinsSplit.getNew().get(0); user1CoinsSplitToUser2.check(); user1CoinsSplitToUser2.traceErrors(); user2CoinsSplitToUser1.check(); user2CoinsSplitToUser1.traceErrors(); System.out.println("--- procedure for exchange of contracts ---"); Contract swapContract; swapContract = ContractsService.startSwap(user1CoinsSplitToUser2, user2CoinsSplitToUser1, user1PrivateKeySet, user2PublicKeySet, false); ContractsService.signPresentedSwap(swapContract, user2PrivateKeySet); ContractsService.finishSwap(swapContract, user1PrivateKeySet); user1CoinsSplit.seal(); user2CoinsSplit.seal(); swapContract.getNewItems().clear(); swapContract.addNewItems(user1CoinsSplit, user2CoinsSplit); swapContract.seal(); swapContract.check(); swapContract.traceErrors(); System.out.println("Transaction contract for swapping is valid: " + swapContract.isOk()); swapContract = Contract.fromPackedTransaction(swapContract.getPackedTransaction()); main.node.registerItem(swapContract); assertEquals(ItemState.APPROVED, main.node.waitItem(swapContract.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user1CoinsSplit.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user2CoinsSplit.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user1CoinsSplitToUser2.getId(), 5000).state); assertEquals(ItemState.APPROVED, main.node.waitItem(user2CoinsSplitToUser1.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(contractTOK92.getId(), 5000).state); assertEquals(ItemState.REVOKED, main.node.waitItem(contractTOK93.getId(), 5000).state); assertEquals("8.02", user1CoinsSplitToUser2.getStateData().getStringOrThrow("amount")); assertEquals("10.01", user2CoinsSplitToUser1.getStateData().getStringOrThrow("amount")); assertFalse(user1CoinsSplitToUser2.getOwner().isAllowedForKeys(user1PublicKeySet)); assertTrue(user1CoinsSplitToUser2.getOwner().isAllowedForKeys(user2PublicKeySet)); assertTrue(user2CoinsSplitToUser1.getOwner().isAllowedForKeys(user1PublicKeySet)); assertFalse(user2CoinsSplitToUser1.getOwner().isAllowedForKeys(user2PublicKeySet)); mm.forEach(x -> x.shutdown()); }
@Test public void testAddReferenceApi() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PrivateKey> llcPrivateKeys = new HashSet<>(); Set<PrivateKey> thirdPartyPrivateKeys = new HashSet<>(); llcPrivateKeys.add(new PrivateKey(Do.read(ROOT_PATH + "_xer0yfe2nn1xthc.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(ROOT_PATH + "keys/stepan_mamontov.private.unikey"))); thirdPartyPrivateKeys.add(new PrivateKey(Do.read(ROOT_PATH + "keys/marty_mcfly.private.unikey"))); Set<PublicKey> stepaPublicKeys = new HashSet<>(); for (PrivateKey pk : stepaPrivateKeys) { stepaPublicKeys.add(pk.getPublicKey()); } Set<PublicKey> thirdPartyPublicKeys = new HashSet<>(); for (PrivateKey pk : thirdPartyPrivateKeys) { thirdPartyPublicKeys.add(pk.getPublicKey()); } Contract jobCertificate = new Contract(llcPrivateKeys.iterator().next()); jobCertificate.setOwnerKeys(stepaPublicKeys); jobCertificate.getDefinition().getData().set("issuer", "ApricoT"); jobCertificate.getDefinition().getData().set("type", "chief accountant assignment"); jobCertificate.seal(); jobCertificate.check(); jobCertificate.traceErrors(); ItemResult itemResult = client.register(jobCertificate.getPackedTransaction(), 5000); System.out.println("sourceContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(jobCertificate.getId()).state); Contract llcProperty = ContractsService.createNotaryContract(llcPrivateKeys, stepaPublicKeys); List<String> listConditions = new ArrayList<>(); listConditions.add("ref.definition.issuer == \"HggcAQABxAACzHE9ibWlnK4RzpgFIB4jIg3WcXZSKXNAqOTYUtGXY03xJSwpqE+y/HbqqE0WsmcAt5\n" + " a0F5H7bz87Uy8Me1UdIDcOJgP8HMF2M0I/kkT6d59ZhYH/TlpDcpLvnJWElZAfOytaICE01bkOkf6M\n" + " z5egpToDEEPZH/RXigj9wkSXkk43WZSxVY5f2zaVmibUZ9VLoJlmjNTZ+utJUZi66iu9e0SXupOr/+\n" + " BJL1Gm595w32Fd0141kBvAHYDHz2K3x4m1oFAcElJ83ahSl1u85/naIaf2yuxiQNz3uFMTn0IpULCM\n" + " vLMvmE+L9io7+KWXld2usujMXI1ycDRw85h6IJlPcKHVQKnJ/4wNBUveBDLFLlOcMpCzWlO/D7M2Iy\n" + " Na8XEvwPaFJlN1UN/9eVpaRUBEfDq6zi+RC8MaVWzFbNi913suY0Q8F7ejKR6aQvQPuNN6bK6iRYZc\n" + " hxe/FwWIXOr0C0yA3NFgxKLiKZjkd5eJ84GLy+iD00Rzjom+GG4FDQKr2HxYZDdDuLE4PEpYSzEB/8\n" + " LyIqeM7dSyaHFTBII/sLuFru6ffoKxBNk/cwAGZqOwD3fkJjNq1R3h6QylWXI/cSO9yRnRMmMBJwal\n" + " MexOc3/kPEEdfjH/GcJU0Mw6DgoY8QgfaNwXcFbBUvf3TwZ5Mysf21OLHH13g8gzREm+h8c=\""); listConditions.add("ref.definition.data.issuer == \"ApricoT\""); listConditions.add("ref.definition.data.type == \"chief accountant assignment\""); ContractsService.addReferenceToContract(llcProperty, jobCertificate, "certification_contract", Reference.TYPE_EXISTING_DEFINITION, listConditions, true); llcProperty.check(); llcProperty.traceErrors(); itemResult = client.register(llcProperty.getPackedTransaction(), 5000); System.out.println("sourceContract : " + itemResult); assertEquals(ItemState.APPROVED, client.getState(llcProperty.getId()).state); mm.forEach(x -> x.shutdown()); }
@Test public void paymentTest1() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); Main main = mm.get(0); main.config.setIsFreeRegistrationsAllowedFromYaml(true); Client client = new Client(TestKeys.privateKey(20), main.myInfo, null); Contract simpleContract = new Contract(TestKeys.privateKey(1)); simpleContract.seal(); Contract stepaU = InnerContractsService.createFreshU(100000000, new HashSet<>(asList(TestKeys.publicKey(1)))); ItemResult itemResult = client.register(stepaU.getPackedTransaction(), 5000); System.out.println("stepaU itemResult: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); main.config.setIsFreeRegistrationsAllowedFromYaml(false); Parcel parcel = ContractsService.createParcel(simpleContract, stepaU, 1, new HashSet<>(asList(TestKeys.privateKey(1))), false); client.registerParcelWithState(parcel.pack(), 5000); assertEquals(ItemState.APPROVED, client.getState(simpleContract.getId()).state); mm.forEach(x -> x.shutdown()); }
@Test public void concurrentResyncTest() throws Exception { boolean doShutdown = true; PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); TestSpace testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Set<PrivateKey> issuerKeys = new HashSet<>(); Set<PublicKey> ownerKeys = new HashSet<>(); issuerKeys.add(issuerKey); ownerKeys.add(issuerKey.getPublicKey()); ArrayList<Contract> contractsToJoin = new ArrayList<>(); for (int k = 0; k < 4; k++) { if (doShutdown) { if (k < 3) { int absentNode = k + 1; testSpace.nodes.get(absentNode).shutdown(); testSpace.nodes.remove(absentNode); } } Contract contract = new Contract(issuerKey); contract.getDefinition().getData().set("test", "test1"); contract.getStateData().set("amount", "100"); Binder params = Binder.of("field_name", "amount", "join_match_fields", asList("definition.issuer")); Role ownerLink = new RoleLink("@owner_link", "owner"); contract.registerRole(ownerLink); SplitJoinPermission splitJoinPermission = new SplitJoinPermission(ownerLink, params); contract.addPermission(splitJoinPermission); contract.seal(); testSpace.client.register(contract.getPackedTransaction(), 1500); assertEquals(testSpace.client.getState(contract.getId()).state, ItemState.APPROVED); if (doShutdown) { testSpace.nodes.forEach(n -> n.shutdown()); Thread.sleep(2000); testSpace = prepareTestSpace(issuerKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); } contractsToJoin.add(contract); } TestSpace finalTestSpace = testSpace; contractsToJoin.forEach(c -> { int count = 0; for (Main main : finalTestSpace.nodes) { try { if (main.node.waitItem(c.getId(), 4000).state != ItemState.APPROVED) { count++; } } catch (TimeoutException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Contract " + c.getId() + " is unknown to " + count + "node(s)"); }); Contract c = contractsToJoin.remove(Do.randomInt(contractsToJoin.size())); Contract main = c.createRevision(issuerKey); main.getStateData().set("amount", "400"); main.addRevokingItems(contractsToJoin.get(0), contractsToJoin.get(1), contractsToJoin.get(2)); main.addSignerKey(issuerKey); main.seal(); contractsToJoin.add(c); testSpace.client.register(main.getPackedTransaction(), 1500); ItemResult ir; do { ir = testSpace.client.getState(main.getId()); System.out.println(ir); Thread.sleep(1000); } while (ir.state.isPending()); contractsToJoin.forEach(c1 -> { int count = 0; for (Main main1 : finalTestSpace.nodes) { try { if (main1.node.waitItem(c1.getId(), 4000).state != ItemState.APPROVED) { count++; } } catch (TimeoutException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Contract " + c.getId() + " is unknown to " + count + "node(s)"); }); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(x -> x.shutdown()); }
@Test public void tttt() throws Exception { boolean refAsNew = true; PrivateKey key = TestKeys.privateKey(1); TestSpace testSpace = prepareTestSpace(key); testSpace.nodes.forEach(m -> { m.config.setIsFreeRegistrationsAllowedFromYaml(true); }); Contract contractMark = new Contract(key); contractMark.seal(); HashId origin = contractMark.getId(); Contract contractMark2 = new Contract(key); contractMark2.seal(); HashId origin2 = contractMark2.getId(); Contract contract = new Contract(key); SimpleRole issuer = new SimpleRole("issuer"); issuer.addKeyRecord(new KeyRecord(key.getPublicKey())); Reference ref = new Reference(contract); ref.type = Reference.TYPE_EXISTING_STATE; ref.setName(origin.toString()); List<Object> conditionsList = new ArrayList<>(); conditionsList.add(REFERENCE_CONDITION_PREFIX + "\"" + origin.toBase64String() + "\""); conditionsList.add(REFERENCE_CONDITION2); Binder conditions = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList); ref.setConditions(conditions); Reference ref2 = new Reference(contract); ref2.type = Reference.TYPE_EXISTING_STATE; ref2.setName(origin2.toString()); List<Object> conditionsList2 = new ArrayList<>(); conditionsList2.add(REFERENCE_CONDITION_PREFIX + "\"" + origin2.toBase64String() + "\""); conditionsList2.add(REFERENCE_CONDITION2); Binder conditions2 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList2); ref2.setConditions(conditions2); contract.addReference(ref); issuer.addRequiredReference(ref, Role.RequiredMode.ALL_OF); contract.addReference(ref2); issuer.addRequiredReference(ref2, Role.RequiredMode.ALL_OF); contract.registerRole(issuer); contract.setOwnerKeys(key); contract.seal(); ItemResult ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); contract.seal(); contract.getTransactionPack().addReferencedItem(contractMark); contract.getTransactionPack().addReferencedItem(contractMark2); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); if (refAsNew) { contract.addNewItems(contractMark); contract.addNewItems(contractMark2); } else { testSpace.client.register(contractMark.getPackedTransaction(), 5000); testSpace.client.register(contractMark2.getPackedTransaction(), 5000); } contract.seal(); if (!refAsNew) { contract.getTransactionPack().addReferencedItem(contractMark); contract.getTransactionPack().addReferencedItem(contractMark2); } ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); contract = contract.createRevision(key); contract.addSignerKey(key); contract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); contract.seal(); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
@Test public void testMarkReferences5() throws Exception { PrivateKey key = TestKeys.privateKey(1); TestSpace testSpace = prepareTestSpace(key); testSpace.nodes.forEach(m -> { m.config.setIsFreeRegistrationsAllowedFromYaml(true); }); Contract contractMark = new Contract(key); contractMark.seal(); HashId origin = contractMark.getId(); Contract contractMark2 = new Contract(key); contractMark2.seal(); HashId origin2 = contractMark2.getId(); Contract contractMark3 = new Contract(key); contractMark3.seal(); HashId origin3 = contractMark3.getId(); Contract contractMark4 = new Contract(key); contractMark4.seal(); HashId origin4 = contractMark4.getId(); Contract contractMark5 = new Contract(key); contractMark5.seal(); HashId origin5 = contractMark5.getId(); Contract contract = new Contract(key); SimpleRole issuer = new SimpleRole("issuer"); issuer.addKeyRecord(new KeyRecord(key.getPublicKey())); Reference ref = new Reference(contract); ref.type = Reference.TYPE_EXISTING_STATE; ref.setName(origin.toString()); List<Object> conditionsList = new ArrayList<>(); conditionsList.add(REFERENCE_CONDITION_PREFIX + "\"" + origin.toBase64String() + "\""); conditionsList.add(REFERENCE_CONDITION2); Binder conditions = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList); ref.setConditions(conditions); contract.addReference(ref); issuer.addRequiredReference(ref, Role.RequiredMode.ALL_OF); Reference ref2 = new Reference(contract); ref2.type = Reference.TYPE_EXISTING_STATE; ref2.setName(origin2.toString()); List<Object> conditionsList2 = new ArrayList<>(); conditionsList2.add(REFERENCE_CONDITION_PREFIX + "\"" + origin2.toBase64String() + "\""); conditionsList2.add(REFERENCE_CONDITION2); Binder conditions2 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList2); ref2.setConditions(conditions2); contract.addReference(ref2); issuer.addRequiredReference(ref2, Role.RequiredMode.ALL_OF); Reference ref3 = new Reference(contract); ref3.type = Reference.TYPE_EXISTING_STATE; ref3.setName(origin3.toString()); List<Object> conditionsList3 = new ArrayList<>(); conditionsList3.add(REFERENCE_CONDITION_PREFIX + "\"" + origin3.toBase64String() + "\""); conditionsList3.add(REFERENCE_CONDITION2); Binder conditions3 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList3); ref3.setConditions(conditions3); contract.addReference(ref3); issuer.addRequiredReference(ref3, Role.RequiredMode.ALL_OF); Reference ref4 = new Reference(contract); ref4.type = Reference.TYPE_EXISTING_STATE; ref4.setName(origin4.toString()); List<Object> conditionsList4 = new ArrayList<>(); conditionsList4.add(REFERENCE_CONDITION_PREFIX + "\"" + origin4.toBase64String() + "\""); conditionsList4.add(REFERENCE_CONDITION2); Binder conditions4 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList4); ref4.setConditions(conditions4); contract.addReference(ref4); issuer.addRequiredReference(ref4, Role.RequiredMode.ALL_OF); Reference ref5 = new Reference(contract); ref5.type = Reference.TYPE_EXISTING_STATE; ref5.setName(origin5.toString()); List<Object> conditionsList5 = new ArrayList<>(); conditionsList5.add(REFERENCE_CONDITION_PREFIX + "\"" + origin5.toBase64String() + "\""); conditionsList5.add(REFERENCE_CONDITION2); Binder conditions5 = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList5); ref5.setConditions(conditions5); contract.addReference(ref5); issuer.addRequiredReference(ref5, Role.RequiredMode.ALL_OF); contract.registerRole(issuer); contract.setOwnerKeys(key); contract.seal(); ItemResult ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); contract.seal(); contract.getTransactionPack().addReferencedItem(contractMark); contract.getTransactionPack().addReferencedItem(contractMark2); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.DECLINED); contract.addNewItems(contractMark); contract.addNewItems(contractMark2); contract.addNewItems(contractMark3); testSpace.client.register(contractMark4.getPackedTransaction(), 5000); testSpace.client.register(contractMark5.getPackedTransaction(), 5000); contract.seal(); contract.getTransactionPack().addReferencedItem(contractMark4); contract.getTransactionPack().addReferencedItem(contractMark5); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); contract = contract.createRevision(key); contract.addSignerKey(key); contract.setOwnerKeys(TestKeys.privateKey(2).getPublicKey()); contract.seal(); ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
@Test public void conversionSchemeUtoUTN() throws Exception { PrivateKey universaAdminKey = TestKeys.privateKey(10); PrivateKey utnIssuerKey = TestKeys.privateKey(11); PrivateKey uIssuerKey = new PrivateKey(Do.read(Config.uKeyPath)); PrivateKey userKey = TestKeys.privateKey(12); Set<PrivateKey> userKeys = new HashSet<>(); userKeys.add(userKey); SimpleRole universaAdmin = new SimpleRole("universa_admin"); universaAdmin.addKeyRecord(new KeyRecord(universaAdminKey.getPublicKey())); TestSpace testSpace = prepareTestSpace(userKey); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); Set<PrivateKey> utnIssuer = new HashSet<>(); utnIssuer.add(utnIssuerKey); Set<PublicKey> ownerKeys = new HashSet<>(); ownerKeys.add(userKey.getPublicKey()); Contract utnContract = ContractsService.createTokenContract(utnIssuer, ownerKeys, new BigDecimal("100000")); @NonNull ItemResult ir = testSpace.client.register(utnContract.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(utnContract.getId()); } assertEquals(ir.state, ItemState.APPROVED); Contract compound = ContractsService.createSplit(utnContract, new BigDecimal("150"), "amount", new HashSet<>(), true); Contract paymentInUTNs = (Contract) compound.getNewItems().iterator().next(); paymentInUTNs.setOwnerKeys(universaAdminKey); BigDecimal utnsPayed = new BigDecimal(paymentInUTNs.getStateData().getString("amount")); int unitsToIssue = utnsPayed.intValue() * 100; Contract uContract = InnerContractsService.createFreshU(unitsToIssue, ownerKeys); Contract consent = ContractsService.addConsent(uContract, universaAdminKey.getPublicKey().getLongAddress()); uContract.seal(); compound.addNewItems(uContract); consent.addSignerKey(universaAdminKey); consent.seal(); compound.seal(); compound.addSignatureToSeal(userKeys); ir = testSpace.client.register(compound.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(compound.getId()); } assertEquals(ir.state, ItemState.DECLINED); compound.seal(); compound.addSignatureToSeal(userKeys); Contract batch = ContractsService.createBatch(userKeys, compound, consent); ir = testSpace.client.register(batch.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(batch.getId()); } assertEquals(ir.state, ItemState.APPROVED); Contract sampleContract = new Contract(userKey); sampleContract.seal(); Parcel parcel = ContractsService.createParcel(sampleContract, uContract, 1, userKeys); testSpace.client.registerParcelWithState(parcel.pack(), 5000); do { Thread.sleep(500); ir = testSpace.client.getState(sampleContract.getId()); } while (ir.state.isPending()); ItemResult pr = testSpace.client.getState(parcel.getPaymentContract().getId()); assertEquals(pr.state, ItemState.APPROVED); assertEquals(ir.state, ItemState.APPROVED); uContract = parcel.getPaymentContract(); Contract revocation = ContractsService.createRevocation(consent, universaAdminKey); ir = testSpace.client.register(revocation.getPackedTransaction()); while (ir.state.isPending()) { Thread.sleep(500); ir = testSpace.client.getState(revocation.getId()); } assertEquals(ir.state, ItemState.APPROVED); sampleContract = new Contract(userKey); sampleContract.seal(); parcel = ContractsService.createParcel(sampleContract, uContract, 1, userKeys); testSpace.client.registerParcelWithState(parcel.pack(), 5000); do { Thread.sleep(500); ir = testSpace.client.getState(sampleContract.getId()); } while (ir.state.isPending()); assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
@Test public void refTest() throws Exception { PrivateKey key = TestKeys.privateKey(0); Contract contract1 = new Contract(key); Contract contract2 = new Contract(key); Contract contract3 = new Contract(key); Contract contract4 = new Contract(key); contract4.seal(); contract1.addNewItems(contract2); contract3.addNewItems(contract4); Reference reference = new Reference(contract2); reference.name = "consent_" + contract4.getId(); reference.type = Reference.TYPE_EXISTING_STATE; List<Object> conditionsList = new ArrayList<>(); conditionsList.add(REFERENCE_CONDITION_PREFIX + "\"" + contract4.getId().toBase64String() + "\""); conditionsList.add(REFERENCE_CONDITION2); Binder conditions = Binder.of(Reference.conditionsModeType.all_of.name(), conditionsList); reference.setConditions(conditions); contract2.addReference(reference); contract2.getIssuer().addRequiredReference(reference, Role.RequiredMode.ALL_OF); contract3.seal(); contract2.seal(); contract1.seal(); Contract c = ContractsService.createBatch(Do.listOf(key), contract1, contract3); TestSpace testSpace = prepareTestSpace(); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); ItemResult ir = testSpace.client.register(c.getPackedTransaction(), 10000); while (ir.state.isPending()) { ir = testSpace.client.getState(c.getId()); } assertEquals(ir.state, ItemState.APPROVED); testSpace.nodes.forEach(n -> n.shutdown()); }
@Test public void randomReferences() throws Exception { Random random = new Random(); TestSpace testSpace = prepareTestSpace(); testSpace.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true)); final int CONTRACTS_IN_BATCH = 20; final int REFS_COUNT = 1000; List<PrivateKey> keys100 = new ArrayList<>(); for (int i = 0; i < CONTRACTS_IN_BATCH; ++i) keys100.add(new PrivateKey(2048)); List<Contract> contracts100 = new ArrayList<>(); for (int i = 0; i < CONTRACTS_IN_BATCH; ++i) { Contract c = new Contract(keys100.get(i)); c.getStateData().put("some_value", 9000 + random.nextInt(1000)); contracts100.add(c); } Map<Integer, Integer> refsCasesCounter = new HashMap<>(); for (int i = 1; i < REFS_COUNT; ++i) { int refForContract = random.nextInt(keys100.size()); int refCase = random.nextInt(4); refsCasesCounter.put(refCase, refsCasesCounter.getOrDefault(refCase, 0) + 1); Reference ref = new Reference(contracts100.get(refForContract)); switch (refCase) { case 0: ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(Binder.of(Reference.conditionsModeType.all_of.name(), asList("ref.issuer==" + keys100.get(random.nextInt(keys100.size())).getPublicKey().getShortAddress()))); break; case 1: ref.type = Reference.TYPE_EXISTING_DEFINITION; ref.setConditions(Binder.of(Reference.conditionsModeType.all_of.name(), asList("ref.owner==" + keys100.get(random.nextInt(keys100.size())).getPublicKey().getLongAddress()))); break; case 2: ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(Binder.of( Reference.conditionsModeType.all_of.name(), asList( "ref.state.data.some_value==" + contracts100.get(random.nextInt(contracts100.size())).getStateData().getStringOrThrow("some_value") ))); break; case 3: ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(Binder.of( Reference.conditionsModeType.all_of.name(), asList("ref.state.data.some_value<=1000"))); break; } contracts100.get(refForContract).addReference(ref); } System.out.println("\nrefs cases:"); refsCasesCounter.forEach((k, v) -> System.out.println(" case " + k + ": " + v)); Contract batch = new Contract(new PrivateKey(2048)); for (int i = 0; i < keys100.size(); ++i) batch.addNewItems(contracts100.get(i)); batch.seal(); ItemResult ir = testSpace.client.register(batch.getPackedTransaction(), 30000); if (ir.errors.size() > 0) { System.out.println("\n\nerrors:"); ir.errors.forEach(e -> System.out.println(" " + e)); System.out.println(); } assertEquals(ItemState.DECLINED, ir.state); testSpace.nodes.forEach(n -> n.shutdown()); }
@Test public void getStateWithNoLedgerCache() throws Exception { TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0)); testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true)); testSpace.nodes.forEach(m -> ((PostgresLedger) m.node.getLedger()).enableCache(false)); testSpace.nodes.remove(testSpace.nodes.size() - 1).shutdown(); Thread.sleep(4000); Contract rev1 = new Contract(TestKeys.privateKey(0)); rev1.getStateData().set("field1", 33); Permission permission = new ChangeNumberPermission(rev1.getOwner(), Binder.of("field_name", "field1")); rev1.addPermission(permission); rev1.seal(); ItemResult ir1 = testSpace.client.register(rev1.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, ir1.state); Contract rev2 = rev1.createRevision(); rev2.getStateData().set("field1", 34); rev2.addSignerKey(TestKeys.privateKey(0)); rev2.seal(); ItemResult ir2 = testSpace.client.register(rev2.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, ir2.state); ir1 = testSpace.client.register(rev1.getPackedTransaction(), 5000); assertEquals(ItemState.REVOKED, ir1.state); testSpace.nodes.forEach(m -> m.shutdown()); }
@Test public void checkWhiteListKey() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); nc.seal(); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Parcel parcel = createParcelWithFreshU(client, testContract, Do.listOf(myKey)); ItemResult itemResult = client.registerParcelWithState(parcel.pack(), 15000); System.out.println(">> state: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void checkNotWhiteListKey() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } mm.forEach(x -> { x.config.getKeysWhiteList().clear(); x.config.getAddressesWhiteList().clear(); }); Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); nc.seal(); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Set<PublicKey> ownerKeys = new HashSet(); Collection<PrivateKey> keys = Do.listOf(myKey); keys.stream().forEach(key -> ownerKeys.add(key.getPublicKey())); Contract stepaU = InnerContractsService.createFreshU(100000000, ownerKeys); stepaU.check(); stepaU.traceErrors(); PrivateKey clientPrivateKey = client.getSession().getPrivateKey(); PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); client.getSession().setPrivateKey(newPrivateKey); client.restart(); ItemResult itemResult = client.register(stepaU.getPackedTransaction(), 5000); client.getSession().setPrivateKey(clientPrivateKey); client.restart(); assertEquals(itemResult.errors.size(), 1); assertEquals(itemResult.errors.get(0).getMessage(), "command needs client key from whitelist"); assertEquals(ItemState.UNDEFINED, itemResult.state); Set<PrivateKey> keySet = new HashSet<>(); keySet.addAll(keys); Parcel parcel = ContractsService.createParcel(testContract, stepaU, 150, keySet); client.registerParcelWithState(parcel.pack(), 15000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.UNDEFINED, itemResult.state); mm.forEach(x -> x.shutdown()); }
@Test public void checkWhiteListAddress() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); mm.forEach(x -> { x.config.getKeysWhiteList().clear(); x.config.getAddressesWhiteList().clear(); }); mm.forEach(x -> x.config.getAddressesWhiteList().add(new KeyAddress(newPrivateKey.getPublicKey(), 0, true))); Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); nc.seal(); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Set<PublicKey> ownerKeys = new HashSet(); Collection<PrivateKey> keys = Do.listOf(myKey); keys.stream().forEach(key -> ownerKeys.add(key.getPublicKey())); Contract stepaU = InnerContractsService.createFreshU(100000000, ownerKeys); stepaU.check(); stepaU.traceErrors(); PrivateKey clientPrivateKey = client.getSession().getPrivateKey(); client.getSession().setPrivateKey(newPrivateKey); client.restart(); ItemResult itemResult = client.register(stepaU.getPackedTransaction(), 5000); client.getSession().setPrivateKey(clientPrivateKey); client.restart(); assertEquals(ItemState.APPROVED, itemResult.state); Set<PrivateKey> keySet = new HashSet<>(); keySet.addAll(keys); Parcel parcel = ContractsService.createParcel(testContract, stepaU, 150, keySet); client.registerParcelWithState(parcel.pack(), 15000); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println(">> state: " + itemResult); assertEquals(ItemState.APPROVED, itemResult.state); mm.forEach(x -> x.shutdown()); } |
RSAOAEPPublicKey extends AbstractPublicKey { @NonNull @Override public boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); if (saltLength == MAX_SALT_LENGTH) { saltLength = getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize()); } if (saltLength < 0) { throw new RuntimeException(String.format("Incorrect salt length %s", saltLength)); } final Signer signatureChecker = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), saltLength); signatureChecker.init(false, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signatureChecker.update(buffer, 0, howManyBytesRead); } } } return signatureChecker.verifySignature(signature); } } RSAOAEPPublicKey(); RSAOAEPPublicKey(byte[] n, byte[] e, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override boolean canEncrypt(); @Override int getBitStrength(); @Override boolean isInitialized(); @NonNull @Override byte[] encrypt(byte[] plaintext); @NonNull @Override boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength); @NonNull @Override String algorithmTag(); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } | @Test public void checkSignature() throws Exception { AbstractPublicKey rsaPublicKey = pssSpec.getPublicKey(); AbstractPrivateKey rsaPrivateKey = pssSpec.getPrivateKey(); assertArrayEquals( rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), pssSpec.S); assertTrue(rsaPublicKey.checkSignature( pssSpec.M, rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), HashType.SHA1, RSASSAPSSTestVectors.salt.length)); }
@Test public void checkSignatureWithCustomSalt() throws Exception { byte[] e = Hex.decode("010001"); byte[] p = Hex.decode("cd28ffefa9150bd3a8e9b0410e411920ed853c797e41038e9325125bb5fec3258eaba816fcc71ba86a2489da965d825fc0a3dabb31f5190ee80c2a0e7a73c9122e099b8a00c0a819e779e0b2cb07ca71acfb6209d8d607eb58ed314529eced00de559f3201bd3346a64c119cb92290d486a53f77087a232ea3fdb37946ad8e6dc6498da8defc63c30238d2622bcd58f3186e6e3d20f9b2872fd32127236d6eb4b57fa297c9814b2a3881fe2a538ed8d459f7f04faddbffc143f6e02b37d6b648b3c9df51aa7f2425e470ffe105d583c50d1a2da2c89f913a3af90a71ae2fafaff900e09ed4425f2a1c752b7e4f0c54b15640ae9adfd1c9cfcd75717d45a71381"); byte[] q = Hex.decode("fef327944862e322f6dae4649354af28bd32d938b0aeb8a25bf9186e6e3d20f9b2872fd32127236d6eb4b57fa26c2664af885a9e0830cf0a4a4b61d4e3650b3e0dd4507f21f2945479993d6a7d67d960017a42da25e470ff22fd6304e803bcb36cf1ec791ba1e4cc0a88863ca6d8e178a5cba71bb09504e2decfded5a81bbb01e43c02ea8ae795485864f91e3591f864c43da77a5993d213bab24cd9f95a2648f4cba8a56423e7b999b72fa4824f4bd95c5d61f4430e230b71473ef0cc530924654d0cb8c71f4ddba5007ceb93b80a466ec54665f9fe7b9c3804d7ebd13f0768af2d28cefa7240544cd2eb1815fbd40df864dcc4ad8bf4ac05383c56960b17c7"); byte[] nExpected = Hex.decode("cc518b92cef4a1baf1fe3fd3a4419bb5a0a5fe381c7d4b365dd672343a911236474a2fdff759dac21b40af42e83ec8ff30e403ed339faca0ab3a15f72a22dc822184a4949179590cbd53098d443fed61209a47223c4c6212e1b0085824d4ffd7f2d4927533f89a98132d070a61b062873c22b7ae65411a1ea6a9d33d30c5bbe63b19e05fe7589ac50ba5b704ee6fe9338d09dd7e9efd071534646101d058e676c9b650381ff5a0cdb2f11c3167378a25493957cb3ac71770a43cd77bc605b41f11c437560c0a0271154c4782f9c6a731477260e7334a380b81b197c1af53608d9ea451b136afdf7ada9ebba46db0a92464c7283b48a2eb332a89cc70ec02b8c66adc1e2344365db7f7bae30fe793e36eeacc93663969aca23a863556b2b9c4ff690f9f87994fa246c514bec71c91d0df26436934da51a6d484667d5e8f46f3599a8a5f52287dfd019e919ef4650406a44657f59342426ad61d33668b217ffe5f333c1858ce4cbbdcbbb71d486bca83f4eefed82088ea13e8b82288b639446831f61f298e96ebf5281056ed51d5f3e8e25c341386c699f4954a3f33a82efaf88e7d791e311bfbbcc947865349af32ddad1a5addafb10ff7401549a1c53bb7777533e269ec94e73d6f5927662c403a05b7b0541b3af816e91da94bbab8b095fedbb003253deffcbafb4190057f523564646d3f16d9e43a3b8be29a2694942bc047"); RSAOAEPPrivateKey privateKey = new RSAOAEPPrivateKey(e, p, q, HashType.SHA1, HashType.SHA1, new SecureRandom()); RSAOAEPPublicKey publicKey = (RSAOAEPPublicKey) privateKey.getPublicKey(); assertEquals(publicKey.state.keyParameters.getModulus(), BigIntegers.fromUnsignedByteArray(nExpected)); byte[] message = Hex.decode("4655424152206d65616e73204675636b6564205570204265796f756420416c6c205265636f676e6974696f6e"); byte[] signatureExpected = Hex.decode("78def239f5d4809c0557d11407c4825e6afb261873ab9f5d3e3fc22d4faa6c358b81c96d486ae2dbc8ad5ccecec6f49a0d5207579444b85ee4ec9a2d06a737a87717083282c4cf4af1ecc14a4fdfbdaa0d53e139fc77226bc4a01fe55bbc8a29403969911c3599508aaa8701f064b95e7e64b349e320724d6c9e2af5a8556d253bed772fb659bbee0e0a6dfe205d58f71f049b023d9ce8b278eaf3141cec06aab46e78cde55d3c403784819c34741deb681bdc2cee01c41e549f17aeb59ca80b8f045de1cf4ff983599e422bce2e68903d717291d897cf39961577e5fc9af9619379790628dbf369fee707a6a4daa3211ff840b46807351204acb60acc528099f851b8a76b4eaae5f84715ecc971c296f9cf3e058badc544a01e7d1dbef1c353d8704c6cffea9398e7ee6fda895d0dabc8ac18ed88c9497664c867e93e56fbebd4436eb3efa755f8fac3fa627e795be43d92d904fe0a9af989a6c504b1e11617d45b75cb5166795e58e69dfed4bf800f8088b0b48e12600c7f460bdaf34a1999d47ce3f5e11343d1e2b1797fc744aab9fcc938d08f70f91dd30c937e0515f8eb03e1a034044c33fbfbed83df5a1b7145ef0fcbb0f41f909793bd23bd964af1c5a53f72ef7b5920cd77d25cc2d9a7a38cbd86cbb3314222ae1ea3432f1370aefb1ea5780630b5f41c0cd408391537b05e242d0c7e0e6dadfd1de2c6c9500298c3"); int expectedSaltLength = 490; assertTrue(publicKey.checkSignature(message, signatureExpected, HashType.SHA1, expectedSaltLength)); assertTrue(publicKey.checkSignature(message, signatureExpected, HashType.SHA1)); assertFalse(publicKey.checkSignature(message, signatureExpected, HashType.SHA1, 0)); assertTrue(publicKey.checkSignature(message, privateKey.sign(message, HashType.SHA1), HashType.SHA1)); } |
RSAOAEPPublicKey extends AbstractPublicKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("n", BigIntegers.asUnsignedByteArray(state.keyParameters.getModulus())); put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getExponent())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPublicKey(); RSAOAEPPublicKey(byte[] n, byte[] e, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override boolean canEncrypt(); @Override int getBitStrength(); @Override boolean isInitialized(); @NonNull @Override byte[] encrypt(byte[] plaintext); @NonNull @Override boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength); @NonNull @Override String algorithmTag(); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } | @Test public void toHash() throws Exception { AbstractPublicKey rsaPublicKey = oaepSpec.getPublicKey(); Map mapRSA = rsaPublicKey.toHash(); assertArrayEquals((byte[]) mapRSA.get("n"), oaepSpec.n); assertArrayEquals((byte[]) mapRSA.get("e"), oaepSpec.e); assertFalse(mapRSA.containsKey("mgf1Hash")); AbstractPublicKey goodPublicKey1 = new RSAOAEPPublicKey( BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus()), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent()), HashType.SHA512, HashType.SHA512, new SecureRandom()); Map map1 = goodPublicKey1.toHash(); assertArrayEquals((byte[]) map1.get("n"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus())); assertArrayEquals((byte[]) map1.get("e"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent())); assertEquals(map1.get("mgf1Hash"), "SHA-512"); }
@Test public void toHashWithDefaultData() throws Exception { AbstractPublicKey goodPublicKey1 = new RSAOAEPPublicKey( BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus()), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent()), HashType.SHA1, HashType.SHA1, new SecureRandom()); Map map1 = goodPublicKey1.toHash(); assertArrayEquals((byte[]) map1.get("n"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus())); assertArrayEquals((byte[]) map1.get("e"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent())); assertFalse(map1.containsKey("hash")); assertFalse(map1.containsKey("mgf1Hash")); } |
ItemCache { final void cleanUp() { Instant now = Instant.now(); records.values().forEach(r->r.checkExpiration(now)); } ItemCache(Duration maxAge); void shutdown(); @Nullable Approvable get(HashId itemId); @Nullable ItemResult getResult(HashId itemId); void put(Approvable item, ItemResult result); void update(HashId itemId, ItemResult result); void idsCheck(HashId itemId); int size(); } | @Test public void cleanUp() throws Exception { ItemCache c = new ItemCache(Duration.ofMillis(10)); TestItem i1 = new TestItem(true); c.put(i1, ItemResult.UNDEFINED); assertEquals(i1, c.get(i1.getId())); Thread.sleep(11); c.cleanUp(); assertEquals(null, c.get(i1.getId())); } |
PostgresLedger implements Ledger { @Override public StateRecord createOutputLockRecord(long creatorRecordId, HashId newItemHashId) { StateRecord r = new StateRecord(this); r.setState(ItemState.LOCKED_FOR_CREATION); r.setLockedByRecordId(creatorRecordId); r.setId(newItemHashId); try { r.save(); return r; } catch (Failure e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } } PostgresLedger(String connectionString, Properties properties); PostgresLedger(String connectionString); final T inPool(DbPool.DbConsumer<T> consumer); @Override StateRecord getRecord(HashId itemId); @Override StateRecord createOutputLockRecord(long creatorRecordId, HashId newItemHashId); @Override StateRecord getLockOwnerOf(StateRecord rc); @Override StateRecord findOrCreate(HashId itemId); @Override Map<HashId,StateRecord> findUnfinished(); @Override Approvable getItem(final StateRecord record); @Override void putItem(StateRecord record, Approvable item, Instant keepTill); @Override byte[] getKeepingItem(HashId itemId); @Override @Deprecated Object getKeepingByOrigin(HashId origin, int limit); @Override Binder getKeepingBy(String field, HashId id, Binder tags, int limit, int offset, String sortBy, String sortOrder); @Override void putKeepingItem(StateRecord record, Approvable item); @Override void close(); @Override long countRecords(); @Override Map<ItemState, Integer> getLedgerSize(ZonedDateTime createdAfter); @Override T transaction(Callable<T> callable); void testClearLedger(); @Override void destroy(StateRecord record); @Override void markTestRecord(HashId hash); @Override boolean isTestnet(HashId itemId); @Override void save(StateRecord stateRecord); @Override void reload(StateRecord stateRecord); void enableCache(boolean enable); Db getDb(); @Override void saveConfig(NodeInfo myInfo, NetConfig netConfig, PrivateKey nodeKey); @Override Object[] loadConfig(); @Override void addNode(NodeInfo nodeInfo); @Override void removeNode(NodeInfo nodeInfo); void cleanup(boolean isPermanetMode); void savePayment(int amount, ZonedDateTime date); Map<Integer,Integer> getPayments(ZonedDateTime fromDate); @Override NImmutableEnvironment getEnvironment(long environmentId); @Override NImmutableEnvironment getEnvironment(HashId contractId); @Override NImmutableEnvironment getEnvironment(NSmartContract smartContract); @Override void updateSubscriptionInStorage(long subscriptionId, ZonedDateTime expiresAt); @Override void updateStorageExpiresAt(long storageId, ZonedDateTime expiresAt); @Override void saveFollowerEnvironment(long environmentId, ZonedDateTime expiresAt, ZonedDateTime mutedAt, double spent, int startedCallbacks); @Override void updateNameRecord(long nameRecordId, ZonedDateTime expiresAt); @Override Set<HashId> saveEnvironment(NImmutableEnvironment environment); @Override Set<HashId> findBadReferencesOf(Set<HashId> ids); @Override long saveSubscriptionInStorage(HashId hashId, boolean subscriptionOnChain, ZonedDateTime expiresAt, long environmentId); @Override void clearExpiredSubscriptions(); @Override void clearExpiredStorages(); @Override void clearExpiredStorageContractBinaries(); @Override void updateEnvironment(long id, String ncontractType, HashId ncontractHashId, byte[] kvStorage, byte[] transactionPack); @Override Set<Long> getSubscriptionEnviromentIds(HashId id); @Override NCallbackService.FollowerCallbackState getFollowerCallbackStateById(HashId id); @Override Collection<CallbackRecord> getFollowerCallbacksToResyncByEnvId(long environmentId); @Override Collection<CallbackRecord> getFollowerCallbacksToResync(); @Override void addFollowerCallback(HashId id, long environmentId, ZonedDateTime expiresAt, ZonedDateTime storedUntil); @Override void updateFollowerCallbackState(HashId id, NCallbackService.FollowerCallbackState state); @Override void removeFollowerCallback(HashId id); @Override byte[] getSmartContractById(HashId smartContractId); @Override byte[] getContractInStorage(HashId contractId); @Override byte[] getContractInStorage(HashId slotId, HashId contractId); @Override List<byte[]> getContractsInStorageByOrigin(HashId slotId, HashId originId); @Override void removeEnvironmentSubscription(long subscriptionId); @Override void removeEnvironmentStorage(long storageId); @Override long removeEnvironment(HashId ncontractHashId); long getEnvironmentId(HashId ncontractHashId); void removeSubscriptionsByEnvId(long environmentId); void removeStorageContractsByEnvId(long environmentId); @Override void removeExpiredStoragesAndSubscriptionsCascade(); @Override void addNameRecord(final NNameRecord nameRecord); @Override long saveContractInStorage(HashId contractId, byte[] binData, ZonedDateTime expiresAt, HashId origin, long environmentId); @Override void removeNameRecord(NNameRecord nameRecord); @Override void addNameRecordEntry(final NNameRecordEntry nameRecordEntryModel); @Override void removeNameRecordEntry(NNameRecordEntry nameRecordEntry); @Override List<String> isAllNameRecordsAvailable(final Collection<String> reducedNames); @Override List<String> isAllOriginsAvailable(final Collection<HashId> origins); @Override List<String> isAllAddressesAvailable(final Collection<String> addresses); void clearExpiredNameRecords(Duration holdDuration); @Override @Deprecated NNameRecord getNameRecord(final String name); @Override Set<NNameRecord> getNameRecords(final String name); @Override List<NNameRecordEntry> getNameEntries(final long environmentId); @Override @Deprecated List<NNameRecordEntry> getNameEntries(final String nameReduced); @Override List<NNameRecord> getNamesByAddress(String address); @Override List<NNameRecord> getNamesByOrigin(byte[] origin); @Override VoteInfo initiateVoting(Contract contract, ZonedDateTime expiresAt, String roleName, Set<HashId> candidates); @Override VoteInfo getVotingInfo(HashId votingItem); @Override void addVotes(long votingId, long candidateId, List<KeyAddress> votes); @Override List<VoteResult> getVotes(HashId itemId, boolean queryAddresses); @Override void closeVote(HashId itemId); @Override void saveUbotSession(UbotSessionCompact sessionCompact); void saveUbotStorages(HashId executableContractId, ZonedDateTime expiresAt, Map<String, HashId> storages); @Override void saveUbotStorageValue(HashId executableContractId, ZonedDateTime expiresAt, String storageName, HashId value); @Override HashId getUbotStorageValue(HashId executableContractId, String storageName); @Override void getUbotStorages(HashId executableContractId, Map<String, HashId> dest); @Override UbotSessionCompact loadUbotSession(HashId executableContractId); @Override UbotSessionCompact loadUbotSessionByRequestId(HashId requestId); @Override UbotSessionCompact loadUbotSessionById(HashId sessionId); @Override boolean hasUbotSession(HashId executableContractId); @Override void deleteUbotSession(HashId executableContractId); @Override void deleteExpiredUbotSessions(); @Override void deleteExpiredUbotStorages(); @Override void saveUbotTransaction(HashId executableContractId, String transactionName, Binder state); @Override Binder loadUbotTransaction(HashId executableContractId, String transactionName); final static String SEARCH_TAGS; } | @Test public void createOutputLockRecord() throws Exception { ledger.enableCache(true); StateRecord owner = ledger.findOrCreate(HashId.createRandom()); StateRecord other = ledger.findOrCreate(HashId.createRandom()); HashId id = HashId.createRandom(); StateRecord r1 = owner.createOutputLockRecord(id); r1.reload(); assertEquals(id, r1.getId()); assertEquals(ItemState.LOCKED_FOR_CREATION, r1.getState()); assertEquals(owner.getRecordId(), r1.getLockedByRecordId()); StateRecord r2 = owner.createOutputLockRecord(id); assertNull(r2); assertNull(owner.createOutputLockRecord(other.getId())); assertNull(ledger.createOutputLockRecord(owner.getRecordId(), other.getId())); } |
PostgresLedger implements Ledger { @Override public void destroy(StateRecord record) { long recordId = record.getRecordId(); if (recordId == 0) { throw new IllegalStateException("can't destroy record without recordId"); } protect(() -> { inPool(d -> { d.update("DELETE FROM ledger WHERE id = ?", recordId); return null; }); synchronized (cachedRecords) { cachedRecords.remove(record.getId()); } synchronized (cachedRecordsById) { cachedRecordsById.remove(record.getRecordId()); } return null; }); } PostgresLedger(String connectionString, Properties properties); PostgresLedger(String connectionString); final T inPool(DbPool.DbConsumer<T> consumer); @Override StateRecord getRecord(HashId itemId); @Override StateRecord createOutputLockRecord(long creatorRecordId, HashId newItemHashId); @Override StateRecord getLockOwnerOf(StateRecord rc); @Override StateRecord findOrCreate(HashId itemId); @Override Map<HashId,StateRecord> findUnfinished(); @Override Approvable getItem(final StateRecord record); @Override void putItem(StateRecord record, Approvable item, Instant keepTill); @Override byte[] getKeepingItem(HashId itemId); @Override @Deprecated Object getKeepingByOrigin(HashId origin, int limit); @Override Binder getKeepingBy(String field, HashId id, Binder tags, int limit, int offset, String sortBy, String sortOrder); @Override void putKeepingItem(StateRecord record, Approvable item); @Override void close(); @Override long countRecords(); @Override Map<ItemState, Integer> getLedgerSize(ZonedDateTime createdAfter); @Override T transaction(Callable<T> callable); void testClearLedger(); @Override void destroy(StateRecord record); @Override void markTestRecord(HashId hash); @Override boolean isTestnet(HashId itemId); @Override void save(StateRecord stateRecord); @Override void reload(StateRecord stateRecord); void enableCache(boolean enable); Db getDb(); @Override void saveConfig(NodeInfo myInfo, NetConfig netConfig, PrivateKey nodeKey); @Override Object[] loadConfig(); @Override void addNode(NodeInfo nodeInfo); @Override void removeNode(NodeInfo nodeInfo); void cleanup(boolean isPermanetMode); void savePayment(int amount, ZonedDateTime date); Map<Integer,Integer> getPayments(ZonedDateTime fromDate); @Override NImmutableEnvironment getEnvironment(long environmentId); @Override NImmutableEnvironment getEnvironment(HashId contractId); @Override NImmutableEnvironment getEnvironment(NSmartContract smartContract); @Override void updateSubscriptionInStorage(long subscriptionId, ZonedDateTime expiresAt); @Override void updateStorageExpiresAt(long storageId, ZonedDateTime expiresAt); @Override void saveFollowerEnvironment(long environmentId, ZonedDateTime expiresAt, ZonedDateTime mutedAt, double spent, int startedCallbacks); @Override void updateNameRecord(long nameRecordId, ZonedDateTime expiresAt); @Override Set<HashId> saveEnvironment(NImmutableEnvironment environment); @Override Set<HashId> findBadReferencesOf(Set<HashId> ids); @Override long saveSubscriptionInStorage(HashId hashId, boolean subscriptionOnChain, ZonedDateTime expiresAt, long environmentId); @Override void clearExpiredSubscriptions(); @Override void clearExpiredStorages(); @Override void clearExpiredStorageContractBinaries(); @Override void updateEnvironment(long id, String ncontractType, HashId ncontractHashId, byte[] kvStorage, byte[] transactionPack); @Override Set<Long> getSubscriptionEnviromentIds(HashId id); @Override NCallbackService.FollowerCallbackState getFollowerCallbackStateById(HashId id); @Override Collection<CallbackRecord> getFollowerCallbacksToResyncByEnvId(long environmentId); @Override Collection<CallbackRecord> getFollowerCallbacksToResync(); @Override void addFollowerCallback(HashId id, long environmentId, ZonedDateTime expiresAt, ZonedDateTime storedUntil); @Override void updateFollowerCallbackState(HashId id, NCallbackService.FollowerCallbackState state); @Override void removeFollowerCallback(HashId id); @Override byte[] getSmartContractById(HashId smartContractId); @Override byte[] getContractInStorage(HashId contractId); @Override byte[] getContractInStorage(HashId slotId, HashId contractId); @Override List<byte[]> getContractsInStorageByOrigin(HashId slotId, HashId originId); @Override void removeEnvironmentSubscription(long subscriptionId); @Override void removeEnvironmentStorage(long storageId); @Override long removeEnvironment(HashId ncontractHashId); long getEnvironmentId(HashId ncontractHashId); void removeSubscriptionsByEnvId(long environmentId); void removeStorageContractsByEnvId(long environmentId); @Override void removeExpiredStoragesAndSubscriptionsCascade(); @Override void addNameRecord(final NNameRecord nameRecord); @Override long saveContractInStorage(HashId contractId, byte[] binData, ZonedDateTime expiresAt, HashId origin, long environmentId); @Override void removeNameRecord(NNameRecord nameRecord); @Override void addNameRecordEntry(final NNameRecordEntry nameRecordEntryModel); @Override void removeNameRecordEntry(NNameRecordEntry nameRecordEntry); @Override List<String> isAllNameRecordsAvailable(final Collection<String> reducedNames); @Override List<String> isAllOriginsAvailable(final Collection<HashId> origins); @Override List<String> isAllAddressesAvailable(final Collection<String> addresses); void clearExpiredNameRecords(Duration holdDuration); @Override @Deprecated NNameRecord getNameRecord(final String name); @Override Set<NNameRecord> getNameRecords(final String name); @Override List<NNameRecordEntry> getNameEntries(final long environmentId); @Override @Deprecated List<NNameRecordEntry> getNameEntries(final String nameReduced); @Override List<NNameRecord> getNamesByAddress(String address); @Override List<NNameRecord> getNamesByOrigin(byte[] origin); @Override VoteInfo initiateVoting(Contract contract, ZonedDateTime expiresAt, String roleName, Set<HashId> candidates); @Override VoteInfo getVotingInfo(HashId votingItem); @Override void addVotes(long votingId, long candidateId, List<KeyAddress> votes); @Override List<VoteResult> getVotes(HashId itemId, boolean queryAddresses); @Override void closeVote(HashId itemId); @Override void saveUbotSession(UbotSessionCompact sessionCompact); void saveUbotStorages(HashId executableContractId, ZonedDateTime expiresAt, Map<String, HashId> storages); @Override void saveUbotStorageValue(HashId executableContractId, ZonedDateTime expiresAt, String storageName, HashId value); @Override HashId getUbotStorageValue(HashId executableContractId, String storageName); @Override void getUbotStorages(HashId executableContractId, Map<String, HashId> dest); @Override UbotSessionCompact loadUbotSession(HashId executableContractId); @Override UbotSessionCompact loadUbotSessionByRequestId(HashId requestId); @Override UbotSessionCompact loadUbotSessionById(HashId sessionId); @Override boolean hasUbotSession(HashId executableContractId); @Override void deleteUbotSession(HashId executableContractId); @Override void deleteExpiredUbotSessions(); @Override void deleteExpiredUbotStorages(); @Override void saveUbotTransaction(HashId executableContractId, String transactionName, Binder state); @Override Binder loadUbotTransaction(HashId executableContractId, String transactionName); final static String SEARCH_TAGS; } | @Test public void destroy() throws Exception { StateRecord r1 = ledger.findOrCreate(HashId.createRandom()); r1.destroy(); assertNull(ledger.getRecord(r1.getId())); } |
ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); } static String copyOut(Block block); } | @Test public void interceptStdout() throws Exception { String result = ConsoleInterceptor.copyOut(() ->{ System.out.print("hello world"); System.out.print('!'); System.out.println(); System.out.println("foobar"); }); assertEquals("hello world!\nfoobar\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print("hello"); System.out.println(" world!"); }); assertEquals("hello world!\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print(58387); System.out.println(" world!"); }); assertEquals("58387 world!\n", result); } |
Binder extends HashMap<String, Object> implements Serializable { public boolean isFrozen() { return frozen; } Binder(Map copyFrom); Binder(); Binder(Object... keyValuePairs); static Binder fromKeysValues(Object... args); boolean isFrozen(); Double getDouble(String key); String getStringOrThrow(String key); String getString(String key, String defaultValue); String getString(String key); byte[] getBinary(String key); @NonNull byte[] getBinaryOrThrow(String key); @Deprecated boolean getBoolean(String key); Boolean getBoolean(String key, Boolean defaultValue); Boolean getBooleanOrThrow(String key); @Deprecated Binder of(String key); static Binder of(String key, Object value, Object... keysValues); Binder getOrCreateBinder(String key); Binder getBinder(String key); Binder getBinderOrThrow(String key); Binder getBinder(String key, Binder defaultValue); @Deprecated int getInt(String key); int getIntOrThrow(String key); @Deprecated long getLong(String key); long getLong(String key, long defaultValue); Integer getInt(String key, Integer defaultValue); ArrayList<?> getArray(String key); ArrayList<Binder> getBinders(String key); T set(String key, T object); Binder unmodifiableCopy(); void freeze(); static Binder from(Object x); static T convertAllMapsToBinders(Object object); static Binder of(Object x); Binder putAll(String key, Object value, Object... keyValuePairs); ZonedDateTime getZonedDateTime(String key, ZonedDateTime defaultValue); ZonedDateTime getZonedDateTimeOrThrow(String key); long getLongOrThrow(String key); Bytes getBytesOrThrow(String key); T getOrThrow(String key); List<T> getOrCreateList(String key); List<T> getList(String key, List<T> defaultValue); List getListOrThrow(String key); int addToInt(String name, int delta); Binder getBinderOrThrow(String... path); String getStringOrThrow(String... path); T getOrThrow(String... path); T getOrNull(String... path); static final Binder EMPTY; } | @Test public void isFrozen() throws Exception { Binder b = new Binder(); b.put("hello", "world"); Binder x = b.getOrCreateBinder("inner"); x.put("foo", "bar"); assertFalse(b.isFrozen()); assertFalse(b.getBinder("inner").isFrozen()); b.freeze(); assertTrue(b.isFrozen()); assertTrue(b.getBinder("inner").isFrozen()); assertEquals("bar", b.getBinder("inner").get("foo")); Binder e = Binder.EMPTY; assertTrue(e.isFrozen()); x = new Binder(); assertEquals(e, x); assertFalse(b.equals(e)); } |
Binder extends HashMap<String, Object> implements Serializable { @Deprecated public int getInt(String key) { return getIntOrThrow(key); } Binder(Map copyFrom); Binder(); Binder(Object... keyValuePairs); static Binder fromKeysValues(Object... args); boolean isFrozen(); Double getDouble(String key); String getStringOrThrow(String key); String getString(String key, String defaultValue); String getString(String key); byte[] getBinary(String key); @NonNull byte[] getBinaryOrThrow(String key); @Deprecated boolean getBoolean(String key); Boolean getBoolean(String key, Boolean defaultValue); Boolean getBooleanOrThrow(String key); @Deprecated Binder of(String key); static Binder of(String key, Object value, Object... keysValues); Binder getOrCreateBinder(String key); Binder getBinder(String key); Binder getBinderOrThrow(String key); Binder getBinder(String key, Binder defaultValue); @Deprecated int getInt(String key); int getIntOrThrow(String key); @Deprecated long getLong(String key); long getLong(String key, long defaultValue); Integer getInt(String key, Integer defaultValue); ArrayList<?> getArray(String key); ArrayList<Binder> getBinders(String key); T set(String key, T object); Binder unmodifiableCopy(); void freeze(); static Binder from(Object x); static T convertAllMapsToBinders(Object object); static Binder of(Object x); Binder putAll(String key, Object value, Object... keyValuePairs); ZonedDateTime getZonedDateTime(String key, ZonedDateTime defaultValue); ZonedDateTime getZonedDateTimeOrThrow(String key); long getLongOrThrow(String key); Bytes getBytesOrThrow(String key); T getOrThrow(String key); List<T> getOrCreateList(String key); List<T> getList(String key, List<T> defaultValue); List getListOrThrow(String key); int addToInt(String name, int delta); Binder getBinderOrThrow(String... path); String getStringOrThrow(String... path); T getOrThrow(String... path); T getOrNull(String... path); static final Binder EMPTY; } | @Test public void getInt() throws Exception { Binder b = Binder.fromKeysValues( "i1", 100, "i2", "101", "l1", "1505774997427", "l2", 1505774997427L ); assertEquals(100, (int) b.getInt("i1",222)); assertEquals(101, (int) b.getInt("i2",222)); assertEquals(100, b.getIntOrThrow("i1")); assertEquals(101, b.getIntOrThrow("i2")); assertEquals(1505774997427L, b.getLongOrThrow("l1")); assertEquals(1505774997427L, b.getLongOrThrow("l2")); } |
AbstractKey implements Bindable, KeyMatcher { public byte[] fingerprint() { throw new RuntimeException("this key does not support fingerprints"); } byte[] encrypt(byte[] plain); byte[] decrypt(byte[] plain); byte[] sign(InputStream input, HashType hashType); byte[] sign(byte[] input, HashType hashType); boolean verify(InputStream input, byte[] signature, HashType hashType); boolean verify(byte[] input, byte[] signature, HashType hashType); boolean verify(String input, byte[] signature, HashType hashType); KeyInfo info(); byte[] packedInfo(); byte[] pack(); String packToBase64String(); void unpack(byte[] bytes); boolean canSign(); boolean isPublic(); boolean isPrivate(); AbstractKey getPublicKey(); @Override final Binder toBinder(); @Override final T updateFrom(Binder source); static AbstractKey fromBinder(Binder binder); boolean matchType(AbstractKey other); boolean matchTag(AbstractKey other); void setTag(String tag); void setTag(byte[] tag); @Override String toString(); Capsule.KeySource asKeySource(); byte[] fingerprint(); Digest updateDigestWithKeyComponents(Digest digest); byte[] createAnonymousId(); boolean matchAnonymousId(@NonNull byte[] packedId); KeyAddress address(boolean useSha3_384, int keyMark); final KeyAddress getShortAddress(); final KeyAddress getLongAddress(); @Override boolean isMatchingKey(AbstractKey key); @Override final boolean isMatchingKeyAddress(KeyAddress other); static final int FINGERPRINT_SHA256; static final int FINGERPRINT_SHA384; static final int TYPE_PRIVATE; static final int TYPE_PUBLIC; static final int TYPE_PRIVATE_PASSWORD; static final int TYPE_PRIVATE_PASSWORD_V2; } | @Test public void fingerprint() throws Exception { PrivateKey k = TestKeys.privateKey(0); byte[] f1 = k.getPublicKey().fingerprint(); assertEquals(33, f1.length); byte[] f2 = k.fingerprint(); assertArrayEquals(f1, f2); assertEquals(AbstractKey.FINGERPRINT_SHA256, f1[0]); } |
Average { public double average() { if (n < 1) throw new IllegalStateException("too few samples"); return sum / n; } synchronized long update(double value); double average(); double stdev2(); double stdev(); long length(); double correctedStdev(); @Override String toString(); double variation(); } | @Test public void average() throws Exception { Average a = new Average(); for( int i=0; i<5; i++) a.update(i); for( int i=4; i>=0; i--) a.update(i); assertTrue(a.toString().startsWith("2.0±1.414213562373095")); assertEquals(1.490711985, a.correctedStdev(), 0.00001); } |
RunnableWithDynamicPeriod implements Runnable { public void restart() { waitsCount = 0; if (future != null) future.cancel(true); run(); } RunnableWithDynamicPeriod(Runnable lambda, List<Integer> periods, ScheduledExecutorService es); @Override void run(); void cancel(boolean b); void restart(); } | @Test public void testRestart() throws Exception { executorService.submit(() -> System.out.println("warm up executor")); Thread.sleep(1000); List<Integer> periods = Arrays.asList(0,100,100,100,200,400,800,1600,3200,6000); time = System.nanoTime(); AtomicInteger iTick = new AtomicInteger(0); AtomicInteger errorsCount = new AtomicInteger(0); RunnableWithDynamicPeriod r = new RunnableWithDynamicPeriod(() -> { long t1 = System.nanoTime(); long dt = (t1 - time) / 1000000; time = t1; long dt0 = periods.get(Math.min(iTick.get(), periods.size()-1)); System.out.println("tick "+iTick.get()+": " + dt + "ms, must be " + dt0 + "ms"); if (!(Math.abs(dt0 - dt) < 5+dt0/10)) errorsCount.incrementAndGet(); iTick.incrementAndGet(); }, periods, executorService); r.run(); Thread.sleep(8500); r.restart(); iTick.set(0); time = System.nanoTime(); Thread.sleep(10000); System.out.println("executorService.size: " + executorService.getQueue().size()); Assert.assertEquals(1, executorService.getQueue().size()); r.cancel(true); while (executorService.getQueue().size() > 0) { Thread.sleep(1000); System.out.println("executorService.size: " + executorService.getQueue().size()); } Assert.assertEquals(0, executorService.getQueue().size()); Assert.assertEquals(0, errorsCount.get()); } |
RunnableWithDynamicPeriod implements Runnable { public void cancel(boolean b) { synchronized (cancelled) { cancelled.set(true); } } RunnableWithDynamicPeriod(Runnable lambda, List<Integer> periods, ScheduledExecutorService es); @Override void run(); void cancel(boolean b); void restart(); } | @Test public void testCancel() throws Exception { executorService.submit(() -> System.out.println("warm up executor")); Thread.sleep(1000); List<Integer> periods = Arrays.asList(100,100,100,200); time = System.nanoTime(); AtomicInteger iTick = new AtomicInteger(0); AtomicInteger errorsCount = new AtomicInteger(0); RunnableWithDynamicPeriod r = new RunnableWithDynamicPeriod(() -> { long t1 = System.nanoTime(); long dt = (t1 - time) / 1000000; time = t1; long dt0 = periods.get(Math.min(iTick.get(), periods.size()-1)); System.out.println("tick: " + dt + "ms, must be " + dt0 + "ms"); if (!(Math.abs(dt0 - dt) < dt0/10)) errorsCount.incrementAndGet(); iTick.incrementAndGet(); }, periods, executorService); r.run(); System.out.println("wait for ticks"); Thread.sleep(2000); AtomicInteger ticksCount = new AtomicInteger(iTick.get()); System.out.println("now cancel"); r.cancel(true); Thread.sleep(2000); Assert.assertEquals(ticksCount.get(), iTick.get()); } |
BufferedLogger implements AutoCloseable { public List<Entry> slice(long id, int maxEntries) { List<Entry> copy = getCopy(); Entry start = new Entry(id); int fromIndex = Collections.binarySearch(copy, start); if (maxEntries > 0) fromIndex++; if (fromIndex < 0) fromIndex = 0; int toIndex = fromIndex + maxEntries; if (toIndex < fromIndex) { int t = fromIndex; fromIndex = toIndex; toIndex = t; } int length = copy.size(); if (fromIndex < 0) fromIndex = 0; if (toIndex >= length) toIndex = length; if (fromIndex >= length || toIndex < 1 || fromIndex == toIndex) return Collections.emptyList(); return copy.subList(fromIndex, toIndex); } BufferedLogger(int maxEntries); void e(String s); void flush(); boolean flush(long millis); PrintStream printTo(PrintStream ps, boolean printTimestamp); @NonNull Entry log(String message); @NonNull Entry d(String message); @NonNull List<Entry> getLast(int maxEntries); List<Entry> slice(long id, int maxEntries); void clear(); List<Entry> getCopy(); void interceptStdOut(); @Override void close(); void stopInterceptingStdOut(); } | @Test public void slice() throws Exception { BufferedLogger log = new BufferedLogger(100); for (int i = 0; i < 10; i++) { log.log("line " + i); } log.flush(); List<BufferedLogger.Entry> all = log.getCopy(); List<BufferedLogger.Entry> entries = log.slice(all.get(5).id, 3); String result = str(entries); assertEquals("line 6,line 7,line 8", result); result = str(log.slice(all.get(5).id, -3)); assertEquals("line 2,line 3,line 4", result); result = str(log.slice(all.get(2).id, -3)); assertEquals("line 0,line 1", result); result = str(log.slice(all.get(8).id, +3)); assertEquals("line 9", result); result = str(log.slice(all.get(0).id, 20)); assertEquals("line 1,line 2,line 3,line 4,line 5,line 6,line 7,line 8,line 9", result); result = str(log.slice(all.get(9).id, -20)); assertEquals("line 0,line 1,line 2,line 3,line 4,line 5,line 6,line 7,line 8", result); result = str(log.slice(all.get(0).id-1, 20)); assertEquals("line 0,line 1,line 2,line 3,line 4,line 5,line 6,line 7,line 8,line 9", result); } |
BufferedLogger implements AutoCloseable { public @NonNull Entry log(String message) { Entry entry = new Entry(message); queue.add(entry); return entry; } BufferedLogger(int maxEntries); void e(String s); void flush(); boolean flush(long millis); PrintStream printTo(PrintStream ps, boolean printTimestamp); @NonNull Entry log(String message); @NonNull Entry d(String message); @NonNull List<Entry> getLast(int maxEntries); List<Entry> slice(long id, int maxEntries); void clear(); List<Entry> getCopy(); void interceptStdOut(); @Override void close(); void stopInterceptingStdOut(); } | @Test public void log() throws Exception { BufferedLogger log = new BufferedLogger(3); for (int i = 0; i < 10; i++) { log.log("line " + i); } log.flush(); assertEquals("line 7,line 8,line 9", str(log.getCopy())); } |
Do { public static String snakeToCamelCase(String snakeString) { StringBuilder b = new StringBuilder(); for(String s: snakeString.split("_") ) { if(s.length() > 0 ) { b.append(Character.toUpperCase(s.charAt(0))); b.append(s.substring(1, s.length()).toLowerCase()); } } return b.toString(); } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); } | @Test public void snakeToCamelCase() throws Exception { assertEquals("HelloWorld!", Do.snakeToCamelCase("hello_wORld_!")); assertEquals("Hello", Do.snakeToCamelCase("hello_")); assertEquals("Hello", Do.snakeToCamelCase("hello")); assertEquals("Hello", Do.snakeToCamelCase("_hello")); } |
Do { public static <T> T sample(Collection source) { int size = source.size(); if (size <= 0) return null; int i = Do.randomInt(size); if (source instanceof List && source instanceof RandomAccess) return (T) ((List) source).get(i); else return (T) source.toArray()[i]; } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); } | @Test public void sample() throws Exception { HashSet<String> x = new HashSet<>(Do.listOf("aa", "bb", "cc", "cd")); HashSet<String> y = new HashSet<>(); ArrayList<String> z = new ArrayList<>(Do.listOf("aa", "bb", "cc", "cd")); HashSet<String> t = new HashSet<>(); int repetitions = 10000; for (int i = 0; i < repetitions; i++) { y.add(Do.sample(x)); t.add(Do.sample(z)); } assertEquals(y,x); } |
Do { public static int randomInt(int max) { return getRng().nextInt(max); } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); } | @Test public void randomInt() throws Exception { double sum = 0; int repetitions = 20000; int min = 10000, max = -1000; for(int i=0; i < repetitions; i++ ) { int x = Do.randomInt(100); sum += x; if( x < min ) min = x; if( x > max ) max = x; } sum /= repetitions; assertThat( sum, is(closeTo(50, 0.9))); assertThat(min, is(lessThan(20))); assertThat(max, is(greaterThan(80))); } |
DeferredResult { public DeferredResult success(Handler handler) { synchronized (successHandlers) { successHandlers.add(handler); } if (done && success) invokeSuccess(); return this; } DeferredResult success(Handler handler); DeferredResult failure(Handler handler); DeferredResult done(Handler handler); void sendSuccess(Object data); void sendFailure(Object data); boolean isDone(); @SuppressWarnings("unchecked") T getResult(); T waitSuccess(); T await(); T await(long millis); final DeferredResult join(); boolean isSuccess(); final boolean join(long millis); } | @Test public void success() throws Exception { DeferredResult dr = new DeferredResult(); dr.success( (text-> assertEquals("hello", text))); dr.sendSuccess("hello"); } |
AsyncEvent { public void fire(T result) { synchronized (mutex) { this.result = result; fired = true; for (Consumer<T> consumer : consumers) pool.execute(() -> consumer.accept(result)); consumers.clear(); mutex.notifyAll(); } } AsyncEvent<T> addConsumer(Consumer<T> consumer); void fire(T result); boolean isFired(); @Deprecated T waitFired(); T await(); T await(long milliseconds); final void fire(); } | @Test public void fire() throws Exception { for(int n=0; n<500; n++) { AsyncEvent<Integer> event = new AsyncEvent<>(); int values[] = new int[] { 0, 0}; CountDownLatch latch = new CountDownLatch(2); event.addConsumer(i -> { values[0] = i; latch.countDown(); }); event.addConsumer(i -> { values[1] = i; latch.countDown(); }); event.fire(11); int res = event.waitFired(); assertEquals(11, res); latch.await(); assertEquals(11, values[0]); assertEquals(11, values[1]); } } |
AbstractKey implements Bindable, KeyMatcher { public boolean matchAnonymousId(@NonNull byte[] packedId) throws IOException { assert (packedId.length == 64); HMAC hmac = new HMAC(fingerprint()); hmac.update(packedId, 0, 32); byte[] idDigest = Arrays.copyOfRange(packedId, 32, 64); return Arrays.equals(hmac.digest(), idDigest); } byte[] encrypt(byte[] plain); byte[] decrypt(byte[] plain); byte[] sign(InputStream input, HashType hashType); byte[] sign(byte[] input, HashType hashType); boolean verify(InputStream input, byte[] signature, HashType hashType); boolean verify(byte[] input, byte[] signature, HashType hashType); boolean verify(String input, byte[] signature, HashType hashType); KeyInfo info(); byte[] packedInfo(); byte[] pack(); String packToBase64String(); void unpack(byte[] bytes); boolean canSign(); boolean isPublic(); boolean isPrivate(); AbstractKey getPublicKey(); @Override final Binder toBinder(); @Override final T updateFrom(Binder source); static AbstractKey fromBinder(Binder binder); boolean matchType(AbstractKey other); boolean matchTag(AbstractKey other); void setTag(String tag); void setTag(byte[] tag); @Override String toString(); Capsule.KeySource asKeySource(); byte[] fingerprint(); Digest updateDigestWithKeyComponents(Digest digest); byte[] createAnonymousId(); boolean matchAnonymousId(@NonNull byte[] packedId); KeyAddress address(boolean useSha3_384, int keyMark); final KeyAddress getShortAddress(); final KeyAddress getLongAddress(); @Override boolean isMatchingKey(AbstractKey key); @Override final boolean isMatchingKeyAddress(KeyAddress other); static final int FINGERPRINT_SHA256; static final int FINGERPRINT_SHA384; static final int TYPE_PRIVATE; static final int TYPE_PUBLIC; static final int TYPE_PRIVATE_PASSWORD; static final int TYPE_PRIVATE_PASSWORD_V2; } | @Test public void matchAnonymousId() throws Exception { PrivateKey k1 = TestKeys.privateKey(0); byte[] id1 = k1.createAnonymousId(); byte[] id12 = k1.createAnonymousId(); PrivateKey k2 = TestKeys.privateKey(1); byte[] id2 = k2.createAnonymousId(); assertEquals(64, id1.length); assertEquals(64, id12.length); assertEquals(64, id2.length); assertFalse(Arrays.equals(id1, id12)); assertFalse(Arrays.equals(id1, id2)); assertFalse(Arrays.equals(id12, id2)); assertTrue(k1.matchAnonymousId(id1)); assertTrue(k1.matchAnonymousId(id12)); assertTrue(k2.matchAnonymousId(id2)); assertFalse(k2.matchAnonymousId(id1)); assertFalse(k2.matchAnonymousId(id12)); assertFalse(k1.matchAnonymousId(id2)); } |
BossConnector extends BasicConnector implements Connector { @Override public void send(Map<String, Object> data) throws IOException { if( closed.get() ) throw new IOException("connection closed"); bossOut.write(data); } BossConnector(InputStream in, OutputStream out); @Override void send(Map<String, Object> data); @Override Map<String, Object> receive(); } | @Test public void send() throws Exception { StreamConnector sa = new StreamConnector(); BossConnector bsc = new BossConnector(sa.getInputStream(), sa.getOutputStream()); bsc.send(Do.map("hello", "мыльня")); Map<String, Object> res = bsc.receive(); assertEquals(1, res.size()); assertEquals("мыльня", res.get("hello")); }
@Test public void directLoadTest() throws Exception { StreamConnector sa = new StreamConnector(); StreamConnector sb = new StreamConnector(); Farcall fa = new Farcall(new BossConnector(sa.getInputStream(), sb.getOutputStream())); Farcall fb = new Farcall(new BossConnector(sb.getInputStream(), sa.getOutputStream())); int [] counts = new int[2]; fa.start(command -> { if (command.getName().equals("fast")) { counts[0]++; return "fast done"; } else if (command.getName().equals("slow")) { Thread.sleep(3); counts[1]++; return "slow done"; } return null; }); fb.start(); ExecutorService es = Executors.newWorkStealingPool(); ArrayList<Long> times = new ArrayList<>(); for( int rep=0; rep < 7; rep++ ) { ArrayList<Future<?>> futures = new ArrayList<>(); counts[0] = counts[1] = 0; long t = StopWatch.measure(() -> { CompletableFuture<?> cf = new CompletableFuture<>(); for (int r = 0; r < 40; r++) { futures.add(es.submit(() -> { for (int i = 0; i < 10; i++) assertEquals("fast done", fb.send("fast").waitSuccess()); return null; })); futures.add(es.submit(() -> { for (int i = 0; i < 2; i++) assertEquals("slow done", fb.send("slow").waitSuccess()); return null; })); } futures.forEach(f -> { try { f.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }); }); times.add(t); } long t1 = times.get(2); long t2 = times.get(times.size()-1); long mean = (t1 + t2)/2; assertThat((double) Math.abs(t2-t1) / ((double) mean), CoreMatchers.is(lessThan(0.16)) ); } |
JsonConnector extends BasicConnector implements Connector { @Override public void send(Map<String, Object> data) throws IOException { if (closed.get()) throw new IOException("connection closed"); out.write((toJsonString(data) + "\n").getBytes()); } JsonConnector(InputStream in, OutputStream out); @Override void send(Map<String, Object> data); @Override Map<String, Object> receive(); } | @Test(timeout = 100) public void send() throws Exception { StreamConnector sa = new StreamConnector(); JsonConnector jsc = new JsonConnector(sa.getInputStream(), sa.getOutputStream()); jsc.send(Do.map("hello", "мыльня")); Map<String, Object> res = jsc.receive(); assertEquals(1, res.size()); assertEquals("мыльня", res.get("hello")); } |
BiMapper { public @NonNull <T> T serialize(Object x, BiSerializer serializer) { if (x instanceof String || x instanceof Number || x instanceof Boolean || x == null) return (T) x; Class<?> klass = x.getClass(); if (klass.isArray() && !(klass.getComponentType() == byte.class)) { x = Arrays.asList((Object[]) x); } if (x instanceof Collection) { return (T) ((Collection) x).stream() .map(i -> serialize(i, serializer)) .collect(Collectors.toList()); } String canonicalName = klass.getCanonicalName(); BiAdapter adapter = adapters.get(canonicalName); if (adapter == null) { if (x instanceof Map) { Binder serialized = new Binder(); ((Map)x).forEach((k,v) -> serialized.put(serialize(k),serialize(v))); return (T)serialized; } return (T) x; } Binder result = adapter.serialize(x, serializer); String tn = adapter.typeName(); result.put("__type", tn != null ? tn : canonicalName); return (T) result; } BiMapper(); BiMapper(BiMapper parent); void deserializeInPlace(Map map, BiDeserializer deserializer); T deserialize(Map map, BiDeserializer deserializer); T deserialize(Map map); T deserializeObject(Object x); T deserializeObject(Object obj, BiDeserializer deserializer); @NonNull T serialize(Object x, BiSerializer serializer); @NonNull T serialize(Object x); void registerAdapter(Class<T> klass, BiAdapter adapter); boolean unregister(Class klass); void registerClass(Class<? extends BiSerializable> klass); BiSerializer newSerializer(); BiDeserializer newDeserializer(); } | @Test public void serialize() throws Exception { ZonedDateTime now = ZonedDateTime.now(); Binder res = DefaultBiMapper.serialize( Binder.of( "time", now, "hello", "world" ) ); assertEquals("world", res.get("hello")); assertEquals("unixtime", res.getStringOrThrow("time", "__type")); Binder restored = DefaultBiMapper.deserialize(res); assertEquals(now.truncatedTo(ChronoUnit.SECONDS), restored.get("time")); assertEquals(now.truncatedTo(ChronoUnit.SECONDS), DefaultBiMapper.deserialize(DefaultBiMapper.serialize(now))); } |
Informer { public void post(Object event) { int result; int processedCount = invokeCollection(weakInvocations, event); processedCount += invokeCollection(strongInvocations, event); if (processedCount == 0 && !(event instanceof LostEvent)) { post(new LostEvent(event)); } } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); } | @Test public void testPost() throws Exception { Receiver2 receiver = new Receiver2(); informer.registerStrong(receiver); informer.post(123); assertEquals(0, Receiver2.stringCalls); assertEquals(1, Receiver2.objectCalls); assertEquals(123, receiver.lastObject); informer.post("test1"); assertEquals(2, Receiver2.stringCalls); assertEquals(2, Receiver2.objectCalls); assertEquals("test1", receiver.lastObject); assertEquals(0, Receiver2.lostCount); } |
Informer { public void postAfter(final Object event, final long millis) { new Thread(new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(millis); post(event); } catch (InterruptedException e) { } } }).start(); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); } | @Test public void testPostAfter() throws Exception { Receiver1 r1 = new Receiver1(); informer.registerWeak(r1); informer.postAfter(11, 100); assertEquals(0, Receiver1.lostCount); sleep(40); assertEquals(0, Receiver1.lostCount); sleep(70); assertEquals(1, Receiver1.lostCount); } |
Informer { public void registerWeak(Object subscriber) { register(subscriber, true); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); } | @Test public void testRegisterWeak() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerWeak(new Receiver1()); System.gc(); informer.post(11); assertEquals(0, Receiver1.lostCount); } |
Informer { public void registerStrong(Object subscriber) { register(subscriber, false); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); } | @Test public void testRegisterStrong() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerStrong(new Receiver1()); informer.post(11); assertEquals(1, Receiver1.lostCount); } |
Informer { public boolean unregister(Object subscriber) { boolean found = (weakInvocations.remove(subscriber) != null); found = found || (strongInvocations.remove(subscriber) != null); return found; } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); } | @Test public void testUnregister() throws Exception { assertEquals(0, Receiver1.lostCount); Receiver1 r1 = new Receiver1(); informer.registerWeak(r1); informer.unregister(r1); informer.post(11); assertEquals(0, Receiver1.lostCount); informer.registerStrong(r1); informer.unregister(r1); informer.post(11); assertEquals(0, Receiver1.lostCount); } |
Safe58 { public static String encode(byte[] input) { if (input.length == 0) { return ""; } input = copyOfRange(input, 0, input.length); int zeroCount = 0; while (zeroCount < input.length && input[zeroCount] == 0) { ++zeroCount; } byte[] temp = new byte[input.length * 2]; int j = temp.length; int startAt = zeroCount; while (startAt < input.length) { byte mod = divmod58(input, startAt); if (input[startAt] == 0) { ++startAt; } temp[--j] = (byte) ALPHABET[mod]; } while (j < temp.length && temp[j] == ALPHABET[0]) { ++j; } while (--zeroCount >= 0) { temp[--j] = (byte) ALPHABET[0]; } byte[] output = copyOfRange(temp, j, temp.length); return new String(output); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); } | @Test public void encode() { for(int i=0; i<100;i++) { byte [] src = Do.randomBytes(256+Do.randomInt(1024)); assertArrayEquals(src, Safe58.decode(Safe58.encode(src))); } } |
KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } KeyAddress(); KeyAddress(AbstractKey key, int typeMark, boolean useSha3_384); KeyAddress(byte[] packedSource); KeyAddress(String packedString); KeyAddress(Binder binder); @Override boolean isMatchingKey(AbstractKey key); @Override boolean isMatchingKeyAddress(KeyAddress other); final boolean isLong(); final byte[] getPacked(); final int getTypeMark(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static BiAdapter getBiAdapter(); } | @Test public void isMatchingKey() throws KeyAddress.IllegalAddressException { testMatch(true); testMatch(false); } |
Safe58 { public static byte[] decode(String input) { return decode(input,false); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); } | @Test public void decode() { byte[] ok = Safe58.decode("Helloworld"); assertArrayEquals(ok,Safe58.decode("HellOwOr1d")); assertArrayEquals(ok,Safe58.decode("He1IOw0r1d")); assertArrayEquals(ok,Safe58.decode("He!|Ow0r|d")); } |
CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void checkTransactionPack() throws Exception { Contract r = new Contract(ownerKey1); r.seal(); Contract c = r.createRevision(ownerKey1); Contract n = c.split(1)[0]; n.seal(); c.seal(); c.addNewItems(n); String path = rootPath + "/testtranspack.unicon"; c.seal(); Files.deleteIfExists(Paths.get(path)); CLIMain.saveContract(c, path, true, true); callMain("--check", path, "-v"); System.out.println(output); }
@Test public void parsingAndExportRefsTest() throws Exception { Contract refContract = Contract.fromDslFile(rootPath + "ref_conditions_root_contract.yml"); Binder conditions = refContract.getReferences().get("test_ref4").getConditions(); List<Object> condList = conditions.getList(all_of.name(), null); condList.add("\"string\"!=this.state.data.string3"); condList.add("\"==INFORMATION==\"==this.state.data.string2"); condList.add("\"string\"==this.state.data.string4"); refContract.getReferences().get("test_ref4").setConditions(conditions); conditions = refContract.getReferences().get("test_ref3").getConditions(); condList = conditions.getList(all_of.name(), null); Binder parsed = ((Binder)condList.get(0)); assertEquals(parsed.getString("leftOperand", ""), "this.definition.issuer"); assertEquals(parsed.getString("rightOperand", ""), "this.state.issuer"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 0); assertEquals(parsed.getIntOrThrow("operator"), 7); parsed = ((Binder)condList.get(9)); assertEquals(parsed.getString("leftOperand", ""), "this.state.data.bigdecimal_val"); assertEquals(parsed.getString("rightOperand", ""), "123980111893281903812098390128320192830219821321321321123910849732682917138291"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(parsed.getIntOrThrow("leftConversion"), 1); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 1); assertEquals(parsed.getIntOrThrow("operator"), 3); conditions = refContract.getReferences().get("test_ref4").getConditions(); condList = conditions.getList(all_of.name(), null); parsed = ((Binder)condList.get(4)); assertEquals(parsed.getString("leftOperand", ""), "==INFORMATION=="); assertEquals(parsed.getString("rightOperand", ""), "this.state.data.string2"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 1); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 0); assertEquals(parsed.getIntOrThrow("operator"), 7); conditions = refContract.getReferences().get("test_ref_arithmetic").getConditions(); condList = conditions.getList(any_of.name(), null); parsed = ((Binder)condList.get(0)); Binder left = parsed.getBinder("left", null); Binder right = parsed.getBinder("right", null); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 3); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 3); assertEquals(parsed.getIntOrThrow("operator"), 2); assertEquals(left.getString("leftOperand", ""), "this.state.data.double_val"); assertEquals(left.getString("rightOperand", ""), "this.state.data.int_val"); assertEquals(left.getIntOrThrow("rightConversion"), 0); assertEquals(left.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(left.getIntOrThrow("leftConversion"), 0); assertEquals(left.getIntOrThrow("typeOfRightOperand"), 0); assertEquals(left.getIntOrThrow("operation"), 2); assertEquals(right.getString("leftOperand", ""), "this.state.data.bigdecimal_val"); assertEquals(right.getString("rightOperand", ""), "734291738921738179832719873921873920100219.83912839289189189"); assertEquals(right.getIntOrThrow("rightConversion"), 0); assertEquals(right.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(right.getIntOrThrow("leftConversion"), 1); assertEquals(right.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(right.getIntOrThrow("operation"), 1); conditions = ((Binder)condList.get(3)); condList = conditions.getList(all_of.name(), null); parsed = ((Binder)condList.get(0)); left = parsed.getBinder("left", null); assertEquals(parsed.getString("rightOperand", ""), "72"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 3); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(parsed.getIntOrThrow("operator"), 7); assertFalse(parsed.containsKey("leftParentheses")); assertFalse(parsed.containsKey("rightParentheses")); assertEquals(left.getString("leftOperand", ""), "12"); right = left.getBinder("right", null); assertEquals(left.getIntOrThrow("rightConversion"), 0); assertEquals(left.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(left.getIntOrThrow("leftConversion"), 0); assertEquals(left.getIntOrThrow("typeOfRightOperand"), 3); assertEquals(left.getIntOrThrow("operation"), 0); assertFalse(left.containsKey("leftParentheses")); assertFalse(left.containsKey("rightParentheses")); assertEquals(right.getString("leftOperand", ""), "4"); assertEquals(right.getIntOrThrow("rightConversion"), 0); assertEquals(right.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(right.getIntOrThrow("leftConversion"), 0); assertEquals(right.getIntOrThrow("typeOfRightOperand"), 3); assertEquals(right.getIntOrThrow("operation"), 2); assertFalse(right.containsKey("leftParentheses")); assertTrue(right.containsKey("rightParentheses")); right = right.getBinder("right", null); assertEquals(right.getString("leftOperand", ""), "10"); assertEquals(right.getString("rightOperand", ""), "5"); assertEquals(right.getIntOrThrow("rightConversion"), 0); assertEquals(right.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(right.getIntOrThrow("leftConversion"), 0); assertEquals(right.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(right.getIntOrThrow("operation"), 0); assertFalse(right.containsKey("leftParentheses")); assertFalse(right.containsKey("rightParentheses")); parsed = ((Binder)condList.get(5)); left = parsed.getBinder("left", null); assertEquals(parsed.getString("rightOperand", ""), "450.59"); assertEquals(parsed.getIntOrThrow("operator"), 7); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 3); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 2); assertFalse(parsed.containsKey("leftParentheses")); assertFalse(parsed.containsKey("rightParentheses")); assertEquals(left.getString("leftOperand", ""), "450.59012"); assertEquals(left.getString("rightOperand", ""), "3"); assertEquals(left.getIntOrThrow("rightConversion"), 0); assertEquals(left.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(left.getIntOrThrow("leftConversion"), 0); assertEquals(left.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(left.getIntOrThrow("operation"), 100); assertFalse(left.containsKey("leftParentheses")); assertFalse(left.containsKey("rightParentheses")); refContract.addSignerKeyFromFile(rootPath + "_xer0yfe2nn1xthc.private.unikey"); refContract.seal(); refContract.check(); refContract.traceErrors(); CLIMain.saveContract(refContract, basePath + "ref_conditions_root_contract.unicon"); callMain( "-e", basePath + "ref_conditions_root_contract.unicon", "-as", "yaml"); System.out.println(output); assertTrue (output.indexOf("export as yaml ok") >= 0); assertEquals(0, errors.size()); File file = new File( basePath + "ref_conditions_root_contract.yaml"); Scanner scanner = new Scanner(file); List<String> list=new ArrayList<>(); while(scanner.hasNextLine()){ list.add(scanner.nextLine()); } assertTrue((list.contains(" - this.definition.issuer==this.state.issuer"))); assertTrue((list.contains(" - this.owner defined"))); assertTrue((list.contains(" - this.state.data.int_val>37"))); assertTrue((list.contains(" - this.state.data.string_val==\"==DATA==\""))); assertTrue((list.contains(" - false!=this.state.data.boolean_val"))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932<=this.state.data.double_val"))); assertTrue((list.contains(" - this.state.data.string_val!=\"jkdsjdksjakjl12901ndasds_ksdokaoss\""))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.definition.issuer defined"))); assertTrue((list.contains(" - inherits this.state.references.test_ref1"))); assertTrue((list.contains(" - this.state.data.int_val>37"))); assertTrue((list.contains(" - this.state.data.string_val==\"==DATA==\""))); assertTrue((list.contains(" - false!=this.state.data.boolean_val"))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932>this.state.data.double_val"))); assertTrue((list.contains(" - jkdsjdksjakjl12901ndasds_ksdokaoss!=this.state.data.string_val"))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932>this.state.data.double_val"))); assertTrue((list.contains(" - jkdsjdksjakjl12901ndasds_ksdokaoss!=this.state.data.string_val"))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.definition.issuer==this.state.issuer"))); assertTrue((list.contains(" - this.owner defined"))); assertTrue((list.contains(" - this.state.data.int_val>37"))); assertTrue((list.contains(" - this.state.data.string_val==\"==DATA==\""))); assertTrue((list.contains(" - false!=this.state.data.boolean_val"))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932<=this.state.data.double_val"))); assertTrue((list.contains(" - this.state.data.string_val!=\"jkdsjdksjakjl12901ndasds_ksdokaoss\""))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.state.references.test_ref2 is_a this.state.references.test_ref1"))); assertTrue((list.contains(" - this.definition.created_at>this.state.data.time3"))); assertTrue((list.contains(" - this.definition.expires_at<\"2908-04-18 23:58:00\""))); assertTrue((list.contains(" - this.state.data.time5<=this.definition.created_at"))); assertTrue((list.contains(" - '\"string\"!=this.state.data.string3'"))); assertTrue((list.contains(" - '\"==INFORMATION==\"==this.state.data.string2'"))); assertTrue((list.contains(" - '\"string\"==this.state.data.string4'"))); assertTrue((list.contains(" - this.state.data.double_val*this.state.data.int_val<=this.state.data.bigdecimal_val::number-734291738921738179832719873921873920100219.83912839289189189"))); assertTrue((list.contains(" - -67029039209309103.09204932<this.state.data.double_val/382138291832182819.391291092190901"))); assertTrue((list.contains(" - this.state.data.int_val<this.state.data.long_val+37"))); assertTrue((list.contains(" - this.state.data.int_val==1*this.state.data.int_val"))); assertTrue((list.contains(" - this.state.data.long_val==this.state.data.long_val/1+78-78"))); assertTrue((list.contains(" - this.state.data.long_val<=154*7836"))); assertTrue((list.contains(" - -67029039209309103.09204932>this.state.data.double_val-231892.293207"))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298300000+72939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=1239801118932819038120*1123910849732682917138291-8938291839218928/382"))); assertTrue((list.contains(" - 12+4*(10+5)==72"))); assertTrue((list.contains(" - 12+(4)*(10+5)==72"))); assertTrue((list.contains(" - 12+(4*(10+5))==72"))); assertTrue((list.contains(" - (-5)+2<0"))); assertTrue((list.contains(" - (this.state.data.int_val-5)/(43+7)*20==((this.state.data.int_val-5)/10-5)+20"))); assertTrue((list.contains(" - round(450.59012,3)==450.59"))); }
@Test public void findContractsInPath() throws Exception { File dirFile = new File(rootPath + "contract_subfolder/"); if (!dirFile.exists()) dirFile.mkdir(); dirFile = new File(rootPath + "contract_subfolder/contract_subfolder_level2/"); if (!dirFile.exists()) dirFile.mkdir(); List<String> coinValues = Arrays.asList("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "0.3"); List<Contract> listOfCoinsWithAmount = createListOfCoinsWithAmount(coinValues); for (Contract coin : listOfCoinsWithAmount) { int rnd = new Random().nextInt(2); String dir = ""; switch (rnd) { case 0: dir += "contract_subfolder/"; break; case 1: dir += "contract_subfolder/contract_subfolder_level2/"; break; } CLIMain.saveContract(coin, rootPath + dir + "Coin_" + coin.getStateData().getStringOrThrow(FIELD_NAME) + ".unicon"); } Contract nonCoin = Contract.fromDslFile("./src/test_files/simple_root_contract_v2.yml"); nonCoin.seal(); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/NonCoin.unicon"); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/contract_subfolder_level2/NonCoin.unicon"); callMain("-f", rootPath + "contract_subfolder/", "-v", "-r"); System.out.println(output); File[] filesToRemove = new File(rootPath + "contract_subfolder/").listFiles(); for (File file : filesToRemove) { file.delete(); } filesToRemove = new File(rootPath + "contract_subfolder/contract_subfolder_level2/").listFiles(); for (File file : filesToRemove) { file.delete(); } Decimal total = new Decimal(0); for (String i : coinValues) { total = total.add(new Decimal(i)); } System.out.println(output); assertTrue (output.indexOf(total + " (TUNC)") >= 0); }
@Test public void findMintContractsInPath() throws Exception { File dirFile = new File(rootPath + "contract_subfolder/"); if (!dirFile.exists()) dirFile.mkdir(); dirFile = new File(rootPath + "contract_subfolder/contract_subfolder_level2/"); if (!dirFile.exists()) dirFile.mkdir(); List<String> mintContractsHexes = new ArrayList<>(); mintContractsHexes.add("27 33 5F 5F 74 79 70 65 7B 54 72 61 6E 73 61 63 74 69 6F 6E 50 61 63 6B 43 63 6F 6E 74 72 61 63 74 C4 70 05 27 3B 76 65 72 73 69 6F 6E 18 23 74 79 70 65 53 75 6E 69 63 61 70 73 75 6C 65 53 73 69 67 6E 61 74 75 72 65 73 0E C4 A8 02 17 23 65 78 74 73 C4 97 01 27 1B 6B 65 79 BC 21 07 66 EF 93 DB A7 78 84 0B 7C CF 64 DB 9E 07 24 4F F3 6E 48 C7 80 01 EE 46 E4 52 40 A7 3B 90 A8 61 33 73 68 61 35 31 32 BC 40 4D B2 60 99 0D C1 71 E2 1A 2C EF 0D E1 2E 2F 8D AB 2B 89 2B BC 86 13 6C 3F EE 62 CF F5 72 A8 5C 9B 06 A4 54 66 D9 E9 2F 43 66 B0 7E 99 A2 1B 7B 62 40 44 F0 B6 54 B8 39 8E C4 37 68 D9 F9 00 FB 53 63 72 65 61 74 65 64 5F 61 74 79 38 22 70 58 85 3B 70 75 62 5F 6B 65 79 C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD 23 73 69 67 6E C4 00 01 02 3C 70 A1 49 5E 6B A4 BF BF DB 77 82 D3 3C 4C C9 9C 25 E5 F3 CC 7A AD 48 A7 7E 05 6B 32 C0 50 E7 61 43 C1 47 3B 9F 51 92 85 06 75 4E C8 9E 2E B9 33 13 5F A0 6F 6C 70 86 F7 10 CF 6E D5 A6 9E 0B 0D 12 6E F5 09 2D 62 FC 7C B0 54 6F A9 CA 24 8B AB 15 B7 CC 5E 44 95 9A CA 32 FE 57 97 77 AC 0B 15 17 66 0B 3C 4B A3 F3 E3 5E 8D C3 14 F1 E0 AC EB D1 E1 65 2F B4 0C 11 49 9A BD 2E AD 6F AA ED DB EB 54 B6 1F 54 67 02 95 E3 C6 41 2F 03 6B 0F B2 39 DB B9 FE B8 03 13 21 E9 6A F3 9E 35 04 2A 67 6B C5 DD 3A 08 52 BB 15 08 FC 34 E5 05 C2 AB E6 B0 29 A2 22 8D 83 2C 32 A2 6D 39 23 75 EC C3 D3 3F 93 8D 2B 5D 0C BC D2 0F 62 2A EF C2 C5 FB E6 C9 29 8E 72 0A BD DB AE 97 86 5E 08 0F 99 14 B9 7E 05 86 C7 0E 4D F8 11 9A BB 7B 8F 7E 29 0B B3 BF 09 11 FC B2 2A 27 C2 DA 89 FB DA A0 BD 23 64 61 74 61 C4 97 02 1F 43 72 65 76 6F 6B 69 6E 67 06 43 63 6F 6E 74 72 61 63 74 27 33 5F 5F 74 79 70 65 83 55 6E 69 76 65 72 73 61 43 6F 6E 74 72 61 63 74 4B 61 70 69 5F 6C 65 76 65 6C 18 53 64 65 66 69 6E 69 74 69 6F 6E 2F 53 63 72 65 61 74 65 64 5F 61 74 79 22 06 70 58 85 23 64 61 74 61 1F 23 6E 61 6D 65 23 6D 65 77 31 43 63 75 72 72 65 6E 63 79 7D 73 73 68 6F 72 74 5F 63 75 72 72 65 6E 63 79 7D 33 69 73 73 75 65 72 1F 35 53 53 69 6D 70 6C 65 52 6F 6C 65 75 95 4B 61 64 64 72 65 73 73 65 73 0E 17 35 53 4B 65 79 41 64 64 72 65 73 73 43 75 61 64 64 72 65 73 73 BC 25 10 AE 02 80 D9 08 99 1A E5 E4 78 6A 71 D7 48 8F 65 4F 97 8C 89 78 23 D2 D0 9F 9C FE C2 11 F4 2E A6 CB A0 42 33 5B 70 65 72 6D 69 73 73 69 6F 6E 73 1F 33 64 6C 75 79 78 69 1F 35 83 52 65 76 6F 6B 65 50 65 72 6D 69 73 73 69 6F 6E 23 72 6F 6C 65 1F 35 43 52 6F 6C 65 4C 69 6E 6B 75 3B 40 72 65 76 6F 6B 65 5B 74 61 72 67 65 74 5F 6E 61 6D 65 2B 6F 77 6E 65 72 75 33 72 65 76 6F 6B 65 33 76 36 57 57 43 33 3F 53 66 69 65 6C 64 5F 6E 61 6D 65 33 61 6D 6F 75 6E 74 4B 6D 69 6E 5F 76 61 6C 75 65 08 43 6D 69 6E 5F 75 6E 69 74 08 8B 6A 6F 69 6E 5F 6D 61 74 63 68 5F 66 69 65 6C 64 73 16 BB 18 64 65 66 69 6E 69 74 69 6F 6E 2E 64 61 74 61 2E 63 75 72 72 65 6E 63 79 8B 64 65 66 69 6E 69 74 69 6F 6E 2E 69 73 73 75 65 72 35 9B 53 70 6C 69 74 4A 6F 69 6E 50 65 72 6D 69 73 73 69 6F 6E BD 20 1F 35 BD 22 75 5B 40 73 70 6C 69 74 5F 6A 6F 69 6E BD 24 BD 25 75 53 73 70 6C 69 74 5F 6A 6F 69 6E 33 49 73 61 49 36 64 1F 35 AB 43 68 61 6E 67 65 4F 77 6E 65 72 50 65 72 6D 69 73 73 69 6F 6E BD 20 1F 35 BD 22 75 6B 40 63 68 61 6E 67 65 5F 6F 77 6E 65 72 BD 24 BD 25 75 63 63 68 61 6E 67 65 5F 6F 77 6E 65 72 2B 72 6F 6C 65 73 1D 2B 73 74 61 74 65 4F 5D 79 22 06 70 58 85 53 65 78 70 69 72 65 73 5F 61 74 79 12 7E 54 5C 85 53 63 72 65 61 74 65 64 5F 62 79 1F 35 A5 75 3B 63 72 65 61 74 6F 72 AD B5 65 0F BD 2A C0 E8 03 BD 25 1F 35 BD 22 75 BD 25 BD 24 95 43 72 65 76 69 73 69 6F 6E 08 BD 3B 1D 33 70 61 72 65 6E 74 05 33 6F 72 69 67 69 6E 05 1B 6E 65 77 1D 43 73 75 62 49 74 65 6D 73 06 23 6B 65 79 73 0E C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD"); mintContractsHexes.add("27 33 5F 5F 74 79 70 65 7B 54 72 61 6E 73 61 63 74 69 6F 6E 50 61 63 6B 43 63 6F 6E 74 72 61 63 74 C4 6E 06 27 3B 76 65 72 73 69 6F 6E 18 23 74 79 70 65 53 75 6E 69 63 61 70 73 75 6C 65 53 73 69 67 6E 61 74 75 72 65 73 0E C4 A8 02 17 23 65 78 74 73 C4 97 01 27 1B 6B 65 79 BC 21 07 66 EF 93 DB A7 78 84 0B 7C CF 64 DB 9E 07 24 4F F3 6E 48 C7 80 01 EE 46 E4 52 40 A7 3B 90 A8 61 33 73 68 61 35 31 32 BC 40 5D 24 63 80 51 96 37 55 B4 21 88 5A F3 D7 CA FA D0 4A 30 F0 23 0D 39 90 7B 2F 1D 30 42 DC F3 15 99 6F F1 4F 6B 7C EE D4 F2 B2 AD F8 12 52 69 91 C4 9E F3 B4 10 CA 0C 96 AA 16 EB 31 11 42 84 16 53 63 72 65 61 74 65 64 5F 61 74 79 0C 24 70 58 85 3B 70 75 62 5F 6B 65 79 C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD 23 73 69 67 6E C4 00 01 8B 59 27 EB 2C 32 37 A3 F6 D4 B3 09 B2 B3 CE 32 14 FA 55 C6 95 02 0F 78 1D 18 5C AE BA DE FD BF B2 E1 A3 A3 F0 BE 0B F3 7F CC DD EA 8A 1E 47 61 FD 43 F5 39 13 EB 69 76 DC AE 73 9D B7 08 EE 2C 2A C6 16 EF 77 CE 59 28 EA 37 E9 9E FF C8 74 59 48 79 E1 21 07 1F D8 88 F0 AE D5 BE B3 61 25 04 BD 65 6A 31 A4 12 93 EB FE 42 FE 60 5F 36 3C 1B 5E 5C B3 43 08 75 4D 94 5F C3 F1 35 C8 E2 C8 54 BE 67 42 9C 21 E9 F9 19 D3 0C 2D 42 F7 C2 E1 48 B9 21 1F DF D2 1C 06 3C C1 C4 5B 15 E6 42 68 A0 37 7F 15 96 10 63 48 EC D1 DC 9E 79 EB BE 90 5C 9C BC C8 49 35 EF C7 11 53 0E A7 51 E2 3F 9B F1 48 47 D4 19 27 C0 FF E9 AD C9 68 07 73 52 DA 74 A2 DC 53 D7 02 81 26 F6 BE 1C 0C 9A A4 F3 C2 08 42 B0 3C 66 24 9E 81 1D F4 31 7E 9D 22 FB 69 5F 24 C9 DC 30 D0 B3 AE 29 E7 D4 41 89 46 CD 47 99 23 64 61 74 61 C4 95 03 1F 43 72 65 76 6F 6B 69 6E 67 0E 17 33 5F 5F 74 79 70 65 33 48 61 73 68 49 64 53 63 6F 6D 70 6F 73 69 74 65 33 BC 60 9E A0 99 F2 14 85 9B 79 53 88 17 55 78 B8 9B 27 AB 0B E7 85 25 E8 EE 79 8B 7A 6C 34 D0 6F 68 53 E5 3F 6B 19 F8 49 FA 2F 96 4E D2 B6 B9 3D CB 57 27 7C AF 95 27 8F 33 E5 85 8D 74 F6 41 00 65 AA 66 B5 F9 CD 5F 81 6F 42 44 8B CB 59 BA ED C9 6B 38 C1 6B F2 66 86 93 5B CA 9C 63 45 B8 63 7D 48 43 63 6F 6E 74 72 61 63 74 2F 2D 83 55 6E 69 76 65 72 73 61 43 6F 6E 74 72 61 63 74 4B 61 70 69 5F 6C 65 76 65 6C 18 53 64 65 66 69 6E 69 74 69 6F 6E 2F 53 63 72 65 61 74 65 64 5F 61 74 79 62 06 70 58 85 23 64 61 74 61 1F 23 6E 61 6D 65 23 6D 65 77 31 43 63 75 72 72 65 6E 63 79 9D 73 73 68 6F 72 74 5F 63 75 72 72 65 6E 63 79 9D 33 69 73 73 75 65 72 1F 2D 53 53 69 6D 70 6C 65 52 6F 6C 65 95 B5 4B 61 64 64 72 65 73 73 65 73 0E 17 2D 53 4B 65 79 41 64 64 72 65 73 73 43 75 61 64 64 72 65 73 73 BC 25 10 AE 02 80 D9 08 99 1A E5 E4 78 6A 71 D7 48 8F 65 4F 97 8C 89 78 23 D2 D0 9F 9C FE C2 11 F4 2E A6 CB A0 42 33 5B 70 65 72 6D 69 73 73 69 6F 6E 73 1F 33 6B 55 6F 45 4F 44 1F 2D 83 52 65 76 6F 6B 65 50 65 72 6D 69 73 73 69 6F 6E 23 72 6F 6C 65 1F 2D 43 52 6F 6C 65 4C 69 6E 6B 95 3B 40 72 65 76 6F 6B 65 5B 74 61 72 67 65 74 5F 6E 61 6D 65 2B 6F 77 6E 65 72 95 33 72 65 76 6F 6B 65 33 35 38 75 50 4B 77 3F 53 66 69 65 6C 64 5F 6E 61 6D 65 33 61 6D 6F 75 6E 74 4B 6D 69 6E 5F 76 61 6C 75 65 08 43 6D 69 6E 5F 75 6E 69 74 08 8B 6A 6F 69 6E 5F 6D 61 74 63 68 5F 66 69 65 6C 64 73 16 BB 18 64 65 66 69 6E 69 74 69 6F 6E 2E 64 61 74 61 2E 63 75 72 72 65 6E 63 79 8B 64 65 66 69 6E 69 74 69 6F 6E 2E 69 73 73 75 65 72 2D 9B 53 70 6C 69 74 4A 6F 69 6E 50 65 72 6D 69 73 73 69 6F 6E BD 24 1F 2D BD 26 95 5B 40 73 70 6C 69 74 5F 6A 6F 69 6E BD 28 BD 29 95 53 73 70 6C 69 74 5F 6A 6F 69 6E 33 4F 68 48 52 57 57 1F 2D AB 43 68 61 6E 67 65 4F 77 6E 65 72 50 65 72 6D 69 73 73 69 6F 6E BD 24 1F 2D BD 26 95 6B 40 63 68 61 6E 67 65 5F 6F 77 6E 65 72 BD 28 BD 29 95 63 63 68 61 6E 67 65 5F 6F 77 6E 65 72 2B 72 6F 6C 65 73 06 2B 73 74 61 74 65 57 7D 79 0C 24 70 58 85 53 65 78 70 69 72 65 73 5F 61 74 79 52 7E 54 5C 85 53 63 72 65 61 74 65 64 5F 62 79 1F 2D BD 18 95 3B 63 72 65 61 74 6F 72 BD 19 BD 1A 85 0F BD 2E 1B 39 36 37 BD 29 1F 2D BD 26 95 BD 29 BD 28 B5 43 72 65 76 69 73 69 6F 6E 10 BD 3F BD 40 33 70 61 72 65 6E 74 25 33 6F 72 69 67 69 6E 25 4B 62 72 61 6E 63 68 5F 69 64 1B 31 3A 30 6B 74 72 61 6E 73 61 63 74 69 6F 6E 61 6C 05 1B 6E 65 77 0E 17 2D 35 3D BC 60 09 1B EB A6 43 D9 46 06 57 6A 54 81 D2 67 B0 03 7B 8B 2F FF E2 2E BD BD A5 CE E3 0D 69 CF E2 DE 30 0D A8 5B 26 77 28 14 92 B1 1B ED 1D 31 D8 AA 39 AA 46 58 DA 2F E5 74 E6 62 0E B4 60 D7 4A 0F D5 C7 F5 E5 B8 37 CD 30 C8 47 F1 D1 6D 99 45 F4 86 59 35 3E 43 3A 3C 2B AA B6 66 93 26 93 F3 58 43 73 75 62 49 74 65 6D 73 06 23 6B 65 79 73 0E C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD"); for (String hex : mintContractsHexes) { Contract coin = Contract.fromPackedTransaction(Bytes.fromHex(hex).getData()); int rnd = new Random().nextInt(2); String dir = ""; switch (rnd) { case 0: dir += "contract_subfolder/"; break; case 1: dir += "contract_subfolder/contract_subfolder_level2/"; break; } CLIMain.saveContract(coin, rootPath + dir + "Coin_" + coin.getStateData().getStringOrThrow(FIELD_NAME) + ".unicon"); } Contract nonCoin = Contract.fromDslFile("./src/test_files/simple_root_contract_v2.yml"); nonCoin.seal(); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/NonCoin.unicon"); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/contract_subfolder_level2/NonCoin.unicon"); callMain("-f", rootPath + "contract_subfolder/", "-v", "-r"); System.out.println(output); File[] filesToRemove = new File(rootPath + "contract_subfolder/").listFiles(); for (File file : filesToRemove) { file.delete(); } filesToRemove = new File(rootPath + "contract_subfolder/contract_subfolder_level2/").listFiles(); for (File file : filesToRemove) { file.delete(); } Decimal total = new Decimal(1967); System.out.println(output); assertTrue (output.indexOf(total + " (mew1)") >= 0); }
@Test public void checkContractInPathRecursively() throws Exception { File dirFile = new File(rootPath + "contract_subfolder/"); if (!dirFile.exists()) dirFile.mkdir(); dirFile = new File(rootPath + "contract_subfolder/contract_subfolder_level2/"); if (!dirFile.exists()) dirFile.mkdir(); List<String> coinValues = Arrays.asList("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60"); List<Contract> listOfCoinsWithAmount = createListOfCoinsWithAmount(coinValues); for (Contract coin : listOfCoinsWithAmount) { int rnd = new Random().nextInt(2); String dir = ""; switch (rnd) { case 0: dir += "contract_subfolder/"; break; case 1: dir += "contract_subfolder/contract_subfolder_level2/"; break; } CLIMain.saveContract(coin, rootPath + dir + "Coin_" + coin.getStateData().getStringOrThrow(FIELD_NAME) + ".unicon"); } Contract nonCoin = Contract.fromDslFile("./src/test_files/simple_root_contract_v2.yml"); nonCoin.seal(); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/NonCoin.unicon"); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/contract_subfolder_level2/NonCoin.unicon"); callMain("-ch", rootPath, "-v", "-r"); System.out.println(output); File[] filesToRemove = new File(rootPath + "contract_subfolder/").listFiles(); for (File file : filesToRemove) { file.delete(); } filesToRemove = new File(rootPath + "contract_subfolder/contract_subfolder_level2/").listFiles(); for (File file : filesToRemove) { file.delete(); } }
@Test public void revokeCreatedContractWithRole() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); c.setOwnerKeys(goodKey); c.seal(); String contractFileName = basePath + "with_role_for_revoke.unicon"; CLIMain.saveContract(c, contractFileName); System.out.println("---"); System.out.println("register contract"); System.out.println("---"); String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 0); uContract = getApprovedUContract(); callMain2("-revoke", contractFileName, "-k", PRIVATE_KEY_PATH, "-v", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract after revoke"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); }
@Test public void packContractWithCounterParts() throws Exception { String contractFileName = basePath + "coin1000.unicon"; Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(1000)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, contractFileName); callMain2("--check", contractFileName, "-v"); callMain2("-pack-with", contractFileName, "-add-sibling", basePath + "packedContract_new_item.unicon", "-add-revoke", basePath + "packedContract_revoke.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey", "-v"); callMain("--check", contractFileName, "-v"); System.out.println(output); }
@Test public void packContractWithCounterPartsWithName() throws Exception { String contractFileName = basePath + "coin100.unicon"; String savingFileName = basePath + "packed.unicon"; Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, contractFileName); callMain2("--check", contractFileName, "-v"); callMain2("-pack-with", contractFileName, "-add-sibling", basePath + "contract2.unicon", "-add-revoke", basePath + "contract_for_revoke1.unicon", "--output", savingFileName, "-v"); callMain("--check", savingFileName, "-v"); System.out.println(output); }
@Test public void calculateContractProcessingCostFromBinary() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_cost.unicon"); System.out.println("--- cost checking ---"); int costShouldBe = (int) Math.ceil((double)28 / Quantiser.quantaPerU); callMain("--cost", basePath + "contract_for_cost.unicon"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 0); }
@Test public void calculateContractProcessingCostFromManySources() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_cost1.unicon"); CLIMain.saveContract(contract, basePath + "contract_for_cost2.unicon"); System.out.println("--- cost checking ---"); int costShouldBe = (int) Math.ceil((double)28 / Quantiser.quantaPerU); callMain("--cost", basePath + "contract_for_cost1.unicon", basePath + "contract_for_cost2.unicon"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 2); }
@Test public void registerContractAndPrintProcessingCost() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = (int) Math.ceil((double) 28 / Quantiser.quantaPerU); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 0); }
@Test public void registerContractWithPayment() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); Files.deleteIfExists(Paths.get(basePath + "contract_for_register_and_cost.unicon")); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- get u ---"); String uContract = getApprovedUContract(); System.out.println("--- registering contract (with processing cost print) ---"); LogPrinter.showDebug(true); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey", "-amount", "2", "-wait", "5000"); System.out.println(output); assertTrue (output.indexOf("registering the paid contract " + contract.getId() + " from " + basePath + "contract_for_register_and_cost.unicon" + " for 2 U") >= 0); assertTrue (output.indexOf("paid contract " + contract.getId() + " submitted with result: ItemResult<APPROVED") >= 0); }
@Test public void registerContractWithPaymentForStorage() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); Files.deleteIfExists(Paths.get(basePath + "contract_for_register_and_cost.unicon")); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- get u ---"); String uContract = getApprovedUContract(); System.out.println("--- registering contract with paying parcel (with processing cost print) ---"); LogPrinter.showDebug(true); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "-k-contract", PRIVATE_KEY_PATH, "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey", "-amount", "2", "-amount-storage", "100", "-wait", "10000"); System.out.println(output); assertTrue (output.indexOf("registering the paid contract " + contract.getId() + " from " + basePath + "contract_for_register_and_cost.unicon" + " for 2 U (and 100 U for storage)") >= 0); assertTrue (output.indexOf("submitted with result: ItemResult<APPROVED") >= 0); }
@Test public void registerContractAndPrintProcessingCostBreak() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = 28; Contract.setTestQuantaLimit(15); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("ERROR: QUANTIZER_COST_LIMIT") >= 0); Contract.setTestQuantaLimit(-1); }
@Test public void registerContractAndPrintProcessingCostBreakWhileUnpacking() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = 28; Contract.setTestQuantaLimit(1); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("ERROR: QUANTIZER_COST_LIMIT") >= 0); Contract.setTestQuantaLimit(-1); }
@Test public void registerManyContractAndPrintProcessingCost() throws Exception { for (int i = 0; i < 2; i++) { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost" + i + ".unicon"); } System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = (int) Math.ceil((double)28 / Quantiser.quantaPerU); callMain("--register", basePath + "contract_for_register_and_cost0.unicon", basePath + "contract_for_register_and_cost1.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 1); } |
CLIMain { private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void exportPublicKeys() throws Exception { String role = "owner"; callMain( "-e", basePath + "contract_to_export.unicon", "--extract-key", role); System.out.println(output); assertTrue (output.indexOf(role + " export public keys ok") >= 0); assertEquals(0, errors.size()); } |
CLIMain { private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver()); xstream.registerConverter(new MapEntryConverter()); xstream.alias(fieldName, Binder.class); data = Binder.convertAllMapsToBinders(xstream.fromXML(fields.get(fieldName))); } catch (Exception xmlEx) { try { Gson gson = new GsonBuilder().create(); data = Binder.convertAllMapsToBinders(gson.fromJson(fields.get(fieldName), Binder.class)); if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } catch (Exception jsonEx) { try { Yaml yaml = new Yaml(); Object loaded = Binder.convertAllMapsToBinders(yaml.load(fields.get(fieldName))); if (loaded.getClass().equals(Binder.class)) { data = (Binder) loaded; if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } else obj = loaded; } catch (Exception yamlEx) { try { obj = fields.get(fieldName); } catch (Exception ex) { ex.printStackTrace(); xmlEx.printStackTrace(); jsonEx.printStackTrace(); yamlEx.printStackTrace(); } } } } if ((data != null) || (obj != null)) { Binder binder = new Binder(); if (data != null) { BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer(); binder.put("data", bm.deserialize(data)); } else binder.put("data", obj); contract.set(fieldName, binder); report("update field " + fieldName + " ok"); } else { report("update field " + fieldName + " error: no valid data"); } } report("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getExpiresAt())); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void updateFields() throws Exception { ZonedDateTime zdt = ZonedDateTime.now().plusHours(1); String field1 = "definition.issuer"; String value1 = "<definition.issuer>\n" + " <SimpleRole>\n" + " <keys isArray=\"true\">\n" + " <item>\n" + " <KeyRecord>\n" + " <name>Universa</name>\n" + " <key>\n" + " <RSAPublicKey>\n" + " <packed>\n" + " <binary>\n" + " <base64>HggcAQABxAACzHE9ibWlnK4RzpgFIB4jIg3WcXZSKXNAqOTYUtGXY03xJSwpqE+y/HbqqE0W\n" + "smcAt5a0F5H7bz87Uy8Me1UdIDcOJgP8HMF2M0I/kkT6d59ZhYH/TlpDcpLvnJWElZAfOyta\n" + "ICE01bkOkf6Mz5egpToDEEPZH/RXigj9wkSXkk43WZSxVY5f2zaVmibUZ9VLoJlmjNTZ+utJ\n" + "UZi66iu9e0SXupOr/+BJL1Gm595w32Fd0141kBvAHYDHz2K3x4m1oFAcElJ83ahSl1u85/na\n" + "Iaf2yuxiQNz3uFMTn0IpULCMvLMvmE+L9io7+KWXld2usujMXI1ycDRw85h6IJlPcKHVQKnJ\n" + "/4wNBUveBDLFLlOcMpCzWlO/D7M2IyNa8XEvwPaFJlN1UN/9eVpaRUBEfDq6zi+RC8MaVWzF\n" + "bNi913suY0Q8F7ejKR6aQvQPuNN6bK6iRYZchxe/FwWIXOr0C0yA3NFgxKLiKZjkd5eJ84GL\n" + "y+iD00Rzjom+GG4FDQKr2HxYZDdDuLE4PEpYSzEB/8LyIqeM7dSyaHFTBII/sLuFru6ffoKx\n" + "BNk/cwAGZqOwD3fkJjNq1R3h6QylWXI/cSO9yRnRMmMBJwalMexOc3/kPEEdfjH/GcJU0Mw6\n" + "DgoY8QgfaNwXcFbBUvf3TwZ5Mysf21OLHH13g8gzREm+h8c=</base64>\n" + " </binary>\n" + " </packed>\n" + " </RSAPublicKey>\n" + " </key>\n" + " </KeyRecord>\n" + " </item>\n" + " </keys>\n" + " <name>issuer</name>\n" + " </SimpleRole>\n" + " </definition.issuer>"; String field2 = "definition.expires_at"; String value2 = "<definition.expires__at>\n" + " <unixtime>" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss [XXX]").format(zdt) + "</unixtime>\n" + "</definition.expires__at>"; callMain( "-e", basePath + "contract_to_export.unicon", "-set", field1, "-value", value1, "-set", field2, "-value", value2); System.out.println(output); assertTrue (output.indexOf("update field " + field2 + " ok") >= 0); assertTrue (output.indexOf("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(zdt)) >= 0); assertEquals(0, errors.size()); } |
CLIMain { public static Contract downloadContract(String url) { report("downloading from " + url); return null; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void downloadContract() throws Exception { callMain("-d", "www.mainnetwork.io"); System.out.println(output); assertTrue (output.indexOf("downloading from www.mainnetwork.io") >= 0); assertEquals(0, errors.size()); } |
CLIMain { private static void checkContract(Contract contract) { if (!contract.isOk()) { reporter.message("The capsule is not sealed properly:"); contract.getErrors().forEach(e -> reporter.error(e.getError().toString(), e.getObjectName(), e.getMessage())); } Yaml yaml = new Yaml(); if (reporter.isVerboseMode()) { report("api level: " + contract.getApiLevel()); report("contract id: " + contract.getId().toBase64String()); report("issued: " + contract.getIssuedAt()); report("revision: " + contract.getRevision()); report("created: " + contract.getCreatedAt()); report("expires: " + contract.getExpiresAt()); System.out.println(); Set<PublicKey> keys = contract.getSealedByKeys(); contract.getRevoking().forEach(r -> { try { ClientNetwork n = getClientNetwork(); System.out.println(); report("revoking item exists: " + r.getId().toBase64String()); report("\tstate: " + n.check(r.getId())); HashId origin = r.getOrigin(); boolean m = origin.equals(contract.getOrigin()); report("\tOrigin: " + origin); report("\t" + (m ? "matches main contract origin" : "does not match main contract origin")); if( r.canBeRevoked(keys) ) { report("\trevocation is allowed"); } else reporter.error(Errors.BAD_REVOKE.name(), r.getId().toString(), "revocation not allowed"); } catch (Exception clientError) { clientError.printStackTrace(); } }); contract.getNewItems().forEach(n -> { System.out.println(); report("New item exists: " + n.getId().toBase64String()); Contract nc = (Contract) n; boolean m = nc.getOrigin().equals(contract.getOrigin()); report("\tOrigin: " + ((Contract) n).getOrigin()); report("\t" + (m ? "matches main contract origin" : "does not match main contract origin")); }); if (keys.size() > 0) { report("\nSignature contains " + keys.size() + " valid key(s):\n"); keys.forEach(k -> { KeyInfo i = k.info(); report("\t✔︎ " + i.getAlgorythm() + ":" + i.getKeyLength() * 8 + ":" + i.getBase64Tag()); }); report("\nWhich can play roles:\n"); contract.getRoles().forEach((name, role) -> { String canPlay = role.isAllowedForKeys(keys) ? "✔" : "✘"; report("\t" + canPlay + " " + role.getName()); }); report("\nAnd have permissions:\n"); contract.getPermissions().values().forEach(perm -> { String canPlay = perm.isAllowedForKeys(keys) ? "✔" : "✘"; report("\t" + canPlay + " " + perm.getName()); Binder x = DefaultBiMapper.serialize(perm.getParams()); BufferedReader br = new BufferedReader( new StringReader(yaml.dumpAsMap(x) )); try { for (String line; (line = br.readLine()) != null; ) { report("\t " + line); } } catch (IOException e) { e.printStackTrace(); } }); reporter.newLine(); } } Multimap<String, Permission> permissions = contract.getPermissions(); Collection<Permission> sjs = permissions.get("split_join"); if (sjs != null) { sjs.forEach(sj -> checkSj(contract, sj)); } try { contract.check(); } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", contract.toString(), e.getMessage()); } catch (Exception e) { addError(Errors.FAILURE.name(), contract.toString(), e.getMessage()); } addErrors(contract.getErrors()); if (contract.getErrors().size() == 0) { report("Contract is valid"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void checkContract() throws Exception { callMain("-ch", basePath + "contract1.unicon"); System.out.println(output); assertEquals(0, errors.size()); } |
KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } KeyInfo(Algorythm algorythm, byte[] tag, int keyLength); KeyInfo(Algorythm algorythm, byte[] tag); KeyInfo(PRF PRF, int rounds, byte[] salt, byte[] tag); KeyInfo(byte[] packedInfo); byte[] getSalt(); boolean matchType(KeyInfo otherInfo); boolean matchType(AbstractKey otherKey); boolean matchTag(KeyInfo keyInfo); void setTag(byte[] tag); String getBase64Tag(); boolean isPassword(); byte[] getTag(); int getRounds(); Algorythm getAlgorythm(); PRF getPRF(); int getKeyLength(); byte[] pack(); SymmetricKey derivePassword(String password); AbstractKey unpackKey(byte[] data); @Override String toString(); } | @Test public void unpackKey() throws Exception { AbstractKey k1 = TestKeys.privateKey(3).getPublicKey(); AbstractKey kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = SymmetricKey.fromPassword("helluva", 4096); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = TestKeys.privateKey(2); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); } |
CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void revokeContractVirtual() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.addSignerKeyFromFile(rootPath + "keys/u_key.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); c.setOwnerKeys(goodKey); c.seal(); System.out.println("---"); System.out.println("register contract"); System.out.println("---"); CLIMain.registerContract(c); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 0); PrivateKey issuer1 = TestKeys.privateKey(1 ); Contract tc = ContractsService.createRevocation(c, issuer1, goodKey); assertTrue(tc.check()); System.out.println("---"); System.out.println("register revoking contract"); System.out.println("---"); CLIMain.registerContract(tc); Thread.sleep(1500); System.out.println("---"); System.out.println("check revoking contract"); System.out.println("---"); callMain("--probe", tc.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 1); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); }
@Test public void probeFile() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.addSignerKeyFromFile(rootPath + "keys/u_key.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); ((SimpleRole)c.getRole("owner")).addKeyRecord(new KeyRecord(goodKey.getPublicKey())); c.seal(); Files.write(Paths.get(basePath + "probeFile.unicon"),c.getPackedTransaction(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); System.out.println("---"); System.out.println("register contract"); System.out.println("---"); CLIMain.registerContract(c); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe-file", basePath + "probeFile.unicon"); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 0); } |
CLIMain { public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void revokeContract() throws Exception { String contractFileName = basePath + "contract_for_revoke3.unicon"; String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Contract c = CLIMain.loadContract(contractFileName); System.out.println("contract: " + c.getId().toBase64String()); Thread.sleep(1500); System.out.println("probe before revoke"); callMain2("--probe", c.getId().toBase64String(), "--verbose"); Thread.sleep(500); uContract = getApprovedUContract(); callMain2("-revoke", contractFileName, "-k", PRIVATE_KEY_PATH, "-v", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(2500); System.out.println("probe after revoke"); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); } |
CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Test public void revokeContractWithoutKey() throws Exception { String contractFileName = basePath + "contract_for_revoke1.unicon"; String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); callMain2("-revoke", contractFileName, "-v"); Thread.sleep(1500); System.out.println("probe after revoke"); Contract c = CLIMain.loadContract(contractFileName); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) < 0); }
@Test public void revokeTwoContracts() throws Exception { String contractFileName1 = basePath + "contract_for_revoke1.unicon"; String contractFileName2 = basePath + "contract_for_revoke2.unicon"; System.out.println("---"); System.out.println("register contracts"); System.out.println("---"); String uContract = getApprovedUContract(); callMain2("--register", contractFileName1, contractFileName2, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(1500); System.out.println("---"); System.out.println("check u"); System.out.println("---"); uContract = getApprovedUContract(); Contract u = CLIMain.loadContract(uContract); System.out.println("check u " + u.getId().toBase64String()); callMain2("--probe", u.getId().toBase64String(), "--verbose"); System.out.println("---"); System.out.println("revoke contracts"); System.out.println("---"); callMain2("-revoke", contractFileName1, contractFileName2, "-v", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey", "-k", PRIVATE_KEY_PATH); Thread.sleep(1500); System.out.println("---"); System.out.println("check contracts after revoke"); System.out.println("---"); Contract c1 = CLIMain.loadContract(contractFileName1); callMain2("--probe", c1.getId().toBase64String(), "--verbose"); Contract c2 = CLIMain.loadContract(contractFileName2); callMain("--probe", c2.getId().toBase64String(), "--verbose"); Contract u2 = CLIMain.loadContract(uContract); System.out.println("check u " + u2.getId().toBase64String()); callMain2("--probe", u2.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 1); }
@Test public void anonymizeRole() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing.unicon", "-role", "issuer"); assertTrue (new File(basePath + "forRoleAnonymizing_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract = CLIMain.loadContract(basePath + "forRoleAnonymizing_anonymized.unicon", true); assertFalse(contract.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract = new Contract(contract.getLastSealedBinary()); assertFalse(anonPublishedContract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(key.getPublicKey())); }
@Test public void anonymizeAllRoles() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing.unicon"); assertTrue (new File(basePath + "forRoleAnonymizing_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); PrivateKey ownerKey = new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey")); Contract contract = CLIMain.loadContract(basePath + "forRoleAnonymizing_anonymized.unicon", true); assertFalse(contract.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(contract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(contract.getCreator().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract = new Contract(contract.getLastSealedBinary()); assertFalse(anonPublishedContract.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(anonPublishedContract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getCreator().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(ownerKey.getPublicKey())); }
@Test public void anonymizeRoleAndSaveWithName() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing.unicon", "-role", "issuer", "--output", basePath + "myAnon.unicon"); assertTrue (new File(basePath + "myAnon.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract = CLIMain.loadContract(basePath + "myAnon.unicon", true); assertFalse(contract.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract = new Contract(contract.getLastSealedBinary()); assertFalse(anonPublishedContract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(key.getPublicKey())); }
@Test public void anonymizeRoleForTwoContracts() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing1.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing2.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing1.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing1.unicon", basePath + "forRoleAnonymizing2.unicon", "-role", "issuer"); assertTrue (new File(basePath + "forRoleAnonymizing1_anonymized.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract1 = CLIMain.loadContract(basePath + "forRoleAnonymizing1_anonymized.unicon", true); assertFalse(contract1.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract1 = new Contract(contract1.getLastSealedBinary()); assertFalse(anonPublishedContract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(key.getPublicKey())); Contract contract2 = CLIMain.loadContract(basePath + "forRoleAnonymizing2_anonymized.unicon", true); assertFalse(contract2.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract2 = new Contract(contract2.getLastSealedBinary()); assertFalse(anonPublishedContract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(key.getPublicKey())); }
@Test public void anonymizeRoleForTwoContractsWithNames() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing1.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing2.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing1.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing1.unicon", basePath + "forRoleAnonymizing2.unicon", "-role", "issuer", "--output", basePath + "myAnon1.unicon", "--output", basePath + "myAnon2.unicon"); assertTrue (new File(basePath + "myAnon1.unicon").exists()); assertTrue (new File(basePath + "myAnon2.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract1 = CLIMain.loadContract(basePath + "myAnon1.unicon", true); assertFalse(contract1.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract1 = new Contract(contract1.getLastSealedBinary()); assertFalse(anonPublishedContract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(key.getPublicKey())); Contract contract2 = CLIMain.loadContract(basePath + "myAnon2.unicon", true); assertFalse(contract2.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract2 = new Contract(contract2.getLastSealedBinary()); assertFalse(anonPublishedContract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(key.getPublicKey())); }
@Test public void anonymizeAllRolesForTwoContracts() throws Exception { Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing1.unicon")); Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing2.unicon")); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing1.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing2.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing1.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2.unicon").exists()); Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing1_anonymized.unicon")); Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing2_anonymized.unicon")); callMain("-anonymize", basePath + "forRoleAnonymizing1.unicon", basePath + "forRoleAnonymizing2.unicon"); assertTrue (new File(basePath + "forRoleAnonymizing1_anonymized.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); PrivateKey ownerKey = new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey")); Contract contract1 = CLIMain.loadContract(basePath + "forRoleAnonymizing1_anonymized.unicon", true); assertFalse(contract1.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(contract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(contract1.getCreator().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract1 = new Contract(contract1.getLastSealedBinary()); assertFalse(anonPublishedContract1.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(anonPublishedContract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getCreator().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(ownerKey.getPublicKey())); Contract contract2 = CLIMain.loadContract(basePath + "forRoleAnonymizing1_anonymized.unicon", true); assertFalse(contract2.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(contract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(contract2.getCreator().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract2 = new Contract(contract2.getLastSealedBinary()); assertFalse(anonPublishedContract2.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(anonPublishedContract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getCreator().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(ownerKey.getPublicKey())); }
@Test public void sign() throws Exception { PrivateKey key1 = new PrivateKey(2048); PrivateKey key2 = new PrivateKey(2048); Files.write(Paths.get(basePath + "signKey1.privateKey.unikey"),key1.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Files.write(Paths.get(basePath + "signKey2.privateKey.unikey"),key2.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); HashSet<PrivateKey> issuers = new HashSet<>(); issuers.add(key1); HashSet<PublicKey> owners = new HashSet<>(); owners.add(key1.getPublicKey()); Contract contract = ContractsService.createTokenContract(issuers, owners, new BigDecimal("10000.50"), new BigDecimal("0.01")); SimpleRole issuer1 = new SimpleRole("issuer1",contract,new KeyRecord(key1.getPublicKey())); SimpleRole issuer2 = new SimpleRole("issuer2",contract,new KeyRecord(key2.getPublicKey())); ListRole issuer = new ListRole("issuer",contract,ListRole.Mode.ALL,Do.listOf(issuer1,issuer2)); contract.addRole(issuer); contract.seal(); contract.check(); assertFalse(contract.isOk()); Files.write(Paths.get(basePath + "sign.unicon"),contract.getPackedTransaction(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); assertFalse(CLIMain.loadContract(basePath + "sign.unicon").check()); callMain("--sign",basePath + "sign.unicon","--keys",basePath + "signKey2.privateKey.unikey"); callMain("--sign",basePath + "sign.unicon","--keys",basePath + "signKey2.privateKey.unikey","--output", basePath + "sign_2.unicon"); assertTrue(CLIMain.loadContract(basePath + "sign_2.unicon").check()); }
@Test public void createRegisterParcel() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.seal(); String contractFileName = basePath + "createRegisterParcel.unicon"; new FileOutputStream(contractFileName).write(contract.getPackedTransaction()); String uContract = getApprovedUContract(); callMain("--create-parcel", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); callMain("--register-parcel", new FilenameTool(contractFileName).setExtension("uniparcel").toString()); Thread.sleep(1500); System.out.println("probe after register"); Contract c = CLIMain.loadContract(contractFileName); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.APPROVED.name()) > 0); } |
Syntex1 extends Digest { @Override public int getLength() { return 36; } @Override int getLength(); } | @Test public void testBasics() throws Exception { Syntex1 s = new Syntex1(); s.update("Hello world"); byte[] d1 = s.digest(); assertEquals(36, s.getLength()); byte[] d2 = new Syntex1().digest("Fello world"); assertEquals(36, d2.length); byte[] d3 = new Syntex1().digest("Hello world"); assertArrayEquals(d1, d3); assertThat( d3, equalTo(d1)); assertThat( d2, not(equalTo(d1))); InputStream in = new ByteArrayInputStream("Hello world".getBytes()); assertThat(d1, equalTo( new Syntex1().digest(in))); } |
CLIMain { private static void printWallets(List<Wallet> wallets) { reporter.message(""); List<Contract> foundContracts = new ArrayList<>(); for (Wallet wallet : wallets) { foundContracts.addAll(wallet.getContracts()); reporter.message("found wallet: " + wallet.toString()); reporter.verbose(""); HashSet<WalletValueModel> balance = new HashSet<>(); for (Contract contract : wallet.getContracts()) { try { Decimal numcoins = new Decimal(contract.getStateData().getStringOrThrow(AMOUNT_FIELD_NAME)); SplitJoinPermission sjp = (SplitJoinPermission)contract.getPermissions().get("split_join").iterator().next(); WalletValueModel walletValueModel = null; for (WalletValueModel wvm : balance) { if (sjp.validateMergeFields(contract, wvm.contract)) walletValueModel = wvm; } if (walletValueModel == null) walletValueModel = new WalletValueModel(); walletValueModel.value = walletValueModel.value.add(numcoins); String currencyTag = contract.getDefinition().getData().getString("currency_code", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_short_name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("short_currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_name", null); if (currencyTag == null) currencyTag = contract.getOrigin().toString(); walletValueModel.tag = currencyTag; walletValueModel.contract = contract; balance.add(walletValueModel); reporter.verbose("found coins: " + contract.getOrigin().toString() + " -> " + numcoins + " (" + currencyTag + ") "); } catch (Exception e) { e.printStackTrace(); } } reporter.verbose(""); reporter.message("total in the wallet: "); for (WalletValueModel w : balance) { reporter.message(w.value + " (" + w.tag + ") "); } } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } | @Ignore @Test public void printWallets() throws Exception { System.out.println("\n\n"); callMain("-f", "/home/flint/w/uniclient-test", "--verbose"); System.out.println(output); System.out.println("\n\n"); } |
PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); } | @Test public void serializationTest() throws Exception { byte[] packedPublicKey = Do.decodeBase64(publicKey64); PublicKey publicKey = new PublicKey(packedPublicKey); byte[] packedPublicKey2 = publicKey.pack(); assertArrayEquals(packedPublicKey, packedPublicKey2); byte[] packedPrivateKey = Do.decodeBase64(TestKeys.binaryKeys[3]); PrivateKey privateKey = new PrivateKey(packedPrivateKey); byte[] packedPrivateKey2 = privateKey.pack(); assertArrayEquals(packedPrivateKey, packedPrivateKey2); } |
RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError("decrypt failed", e); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } | @Test public void decrypt() throws Exception { AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPrivateKey) rsaPrivateKey).resetDecryptor(); assertArrayEquals(rsaPrivateKey.decrypt(oaepSpec.C), oaepSpec.M); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); AbstractPrivateKey randomPrivateKey = randomPrivateKey4096; AbstractPublicKey randomPublicKey = randomPrivateKey.getPublicKey(); SecureRandom rng = new SecureRandom(); int maxMessageSize = ((RSAOAEPPrivateKey) randomPrivateKey).getMaxBlockSize(), minMessageSize = maxMessageSize, messageSize = (maxMessageSize >= minMessageSize) ? rng.nextInt(maxMessageSize - minMessageSize + 1) + minMessageSize : 0; for (int i = 0; i < NUMBER_OF_RANDOM_ENCRYPTION_DECRYPTION_CYCLES; i++) { ((RSAOAEPPrivateKey) randomPrivateKey).resetDecryptor(); ((RSAOAEPPublicKey) randomPublicKey).resetEncryptor(); byte[] message = new byte[messageSize]; rng.nextBytes(message); byte[] encrypted = randomPublicKey.encrypt(message), decrypted = randomPrivateKey.decrypt(encrypted); assertArrayEquals(decrypted, message); } } |
PrivateKey extends AbstractKey { public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { throw new EncryptionError("the key is public, not private"); } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD) { try { int rounds = (int) params.get(1); Bytes salt = (Bytes) params.get(2); String function = (String) params.get(3); Bytes packedEncryptedKey = (Bytes) params.get(4); Bytes digest = (Bytes) params.get(5); SymmetricKey key = new KeyInfo(KeyInfo.PRF.valueOf(function), rounds, salt.getData(), null) .derivePassword(password); byte[] packedKey = key.decrypt(packedEncryptedKey.getData()); byte[] resDigest = new Crc32().update(packedKey).digest(); if (!digest.equals(new Bytes(resDigest))) { throw new PasswordProtectedException("wrong password"); } return new PrivateKey(packedKey); } catch (Exception e) { if (e instanceof PasswordProtectedException) throw e; throw new EncryptionError("failed to parse password protected private key", e); } } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD_V2) { try { KeyInfo keyInfo = new KeyInfo(((Bytes)params.get(1)).getData()); SymmetricKey key = keyInfo .derivePassword(password); byte[] packedKey = key.etaDecrypt(((Bytes) params.get(2)).getData()); return new PrivateKey(packedKey); } catch (SymmetricKey.AuthenticationFailed authenticationFailed) { throw new PasswordProtectedException("wrong password"); } catch (Exception e) { throw new EncryptionError("failed to parse password protected private key"); } } else { throw new EncryptionError("Bad or unknown private key type"); } } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); } | @Test public void passwordProtectedJsCompatibilityTest() throws Exception { byte[] encrypted = Base64.decodeCompactString("NhDIoIYBvB1jb20uaWNvZGljaS5jcnlwdG8uUHJpdmF0ZUtleVtITUFDX1NIQTI1NsQaAe01NLf/Ffcye5nVmAOsYV5uy/Q/OXqbVfH4baSo5rgdtYl3xmTrkwfHEerHVjyB/raQcJ6b96k3oVIHu6I/wDtZ3TMkQ8gpjzlEnzOs6LQ+0OzObrjxFfpiXZdPMLzu4XPMSJINSZtkPkSOeBEqItCf2C2CfPgdI1MniiDAN9qmuWMuGkD4o6UgaGfCjy0WGv8vY0rgkkQUanf8ctcIEgbLCcpu2irJY+OUhh1qC+Dwm3uSDFarXC/94i/YWpSbo2Apyxjq6ynpXVyc2aQiOmOf13iHulq5t9eyoqP4uSXL4xHff23onQRnvvc4OC+vbQvHType64zPTxVCFDpw6rlUhT/bEJ6IOh8XhX+LHZeTEuaTy0LXE055xiT1P375"); byte[] packed = Base64.decodeCompactString("JgAcAQABvIEA96FWTEq/Wjmd7kYbx04I/Ax3OQV+6e4YWu7xBr8k/SexvYvFEE3c9dRsZSsEj7KzYrNpIXezCsxO+j1sHADmeojwuveDdQQM6M6fbvygHq/mxKGllDoJTpzX/CnkuXDwC+lpRkkMTIF48GaYDM525951HYW1pAIYaVr+V5ctVQW8gQDGM71OC1yBLv6n23dEuu9Vqna2lvDpEWNO7MgKY0Ri9vUPwp+F+dUiKsRTbjnukDFqiYiNj+jkcWgiXqnjqdAGf9LUWHfF80W1PwUhkFw7torLJfaAr6bZ6FRzGcxTMad0x7Rz+5lkBjliKqOt8AUAIvMVe45G0c0StJSoqdqc4Q=="); PrivateKey pk1 = PrivateKey.unpackWithPassword(encrypted,"some-password"); PrivateKey pk2 = new PrivateKey(packed); assertEquals(pk1,pk2); try { PrivateKey.unpackWithPassword(encrypted,"some-password1"); fail("should throw"); } catch (PrivateKey.PasswordProtectedException e) { } } |
PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } | @Test public void computeSha512() { String src = "test $pbkdf$pbkdf2-sha512$5000$26$KFuMDXmo$yPsu5qmQto99vDqAMWnldNuagfVl5OhPr6g="; String[] parts = src.split("\\$"); String password = parts[0].trim(); int c = Integer.valueOf(parts[3]); int dkLen = Integer.valueOf(parts[4]); byte[] salt = Do.decodeBase64(parts[5]); byte[] DK = Do.decodeBase64(parts[6]); assertArrayEquals(DK, PBKDF2.derive(Sha512.class, password, salt, c, dkLen)); }
@Test public void computeSha1() throws Exception { String P = "password"; byte[] S = "salt".getBytes(); int c = 1; int dkLen = 20; byte[] DK = Hex.decode("0c 60 c8 0f 96 1f 0e 71\n" + "f3 a9 b5 24 af 60 12 06\n" + "2f e0 37 a6"); final byte[] key = PBKDF2.derive(Sha1.class, P, S, c, dkLen); assertArrayEquals(DK, key); }
@Test public void computeSha256() throws Exception { String P = "password"; byte[] S = "salt".getBytes(); int c = 1; int dkLen = 32; byte [] DK = Hex.decode("12 0f b6 cf fc f8 b3 2c\n" + "43 e7 22 52 56 c4 f8 37\n" + "a8 65 48 c9 2c cc 35 48\n" + "08 05 98 7c b7 0b e1 7b"); byte[] key = PBKDF2.derive(Sha256.class, P, S, c, dkLen); assertArrayEquals(DK, key); c = 2; DK = Hex.decode("ae 4d 0c 95 af 6b 46 d3\n" + " 2d 0a df f9 28 f0 6d d0\n" + " 2a 30 3f 8e f3 c2 51 df\n" + " d6 e2 d8 5a 95 47 4c 43"); c = 4096; DK = Hex.decode("c5 e4 78 d5 92 88 c8 41\n" + " aa 53 0d b6 84 5c 4c 8d\n" + " 96 28 93 a0 01 ce 4e 11\n" + " a4 96 38 73 aa 98 13 4a"); key = PBKDF2.derive(Sha256.class, P, S, c, dkLen); assertArrayEquals(DK, key); } |
KeyRing implements Capsule.KeySource, Bindable { @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else result.add(k); } } return result; } @Override Binder toBinder(); static KeyRing fromBinder(Binder source); @Override KeyRing updateFrom(Binder source); void clear(); void addKey(AbstractKey key); boolean removeKey(AbstractKey key); @Override @NonNull Collection<AbstractKey> findKey(KeyInfo keyInfo); void addKeys(AbstractKey... newKeys); @Override boolean equals(Object obj); @Override String toString(); boolean contains(AbstractKey k); } | @Test public void findKey() throws Exception { KeyInfo i1 = new KeyInfo(KeyInfo.PRF.HMAC_SHA256, 1024, null, null); AbstractKey pk1 = i1.derivePassword("helluva"); KeyInfo i2 = new KeyInfo(KeyInfo.PRF.HMAC_SHA256, 1025, null, "the tag".getBytes()); AbstractKey pk2 = i2.derivePassword("helluva"); assertEquals(i2.getTag(), pk2.info().getTag()); KeyRing kr = new KeyRing(); SymmetricKey sk1 = new SymmetricKey(); SymmetricKey sk2 = new SymmetricKey(); AbstractKey privateKey = TestKeys.privateKey(0); AbstractKey publicKey1 =TestKeys.privateKey(1).getPublicKey(); AbstractKey publicKey2 = privateKey.getPublicKey(); kr.addKeys( sk1, sk2, privateKey, publicKey1, publicKey2, pk1, pk2 ); kr.addKeys(pk1, pk2); Binder b = kr.toBinder(); KeyRing kr2 = KeyRing.fromBinder(b); assertTrue(kr.keySet().contains(pk1)); assertTrue(kr.keySet().contains(pk2)); assertEquals(pk2, kr.findKey(i2).toArray()[0]); assertEquals(pk2, kr2.findKey(i2).toArray()[0]); final Collection<AbstractKey> keys = kr.findKey(i1); assertTrue(keys.contains(pk1)); assertTrue(keys.contains(pk1)); assertTrue(keys.contains(sk1)); assertTrue(keys.contains(sk2)); assertEquals(4, kr2.findKey(i1).size()); } |
SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test public void etaEncrypt() throws Exception { SymmetricKey k = new SymmetricKey(); byte[] plainText = "Hello, world!".getBytes(); byte[] cipherText = k.etaEncrypt(plainText); assertEquals(16 + 32 + plainText.length, cipherText.length); byte[] decryptedText = k.etaDecrypt(cipherText); assertArrayEquals(plainText, decryptedText); exception.expect(SymmetricKey.AuthenticationFailed.class); cipherText[19] += 1; k.etaDecrypt(cipherText); } |
SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); } | @Test public void xor() throws Exception { byte[] test = new byte[]{0, 0x55, (byte) 0xFF}; byte[] src = new byte[]{0, 0x55, (byte) 0xFF}; test = SymmetricKey.xor(test, 0); assertArrayEquals(test, src); test = SymmetricKey.xor(test, 0xFF); assertArrayEquals(new byte[]{(byte) 0xFF, (byte) 0xAA, 0}, test); test = SymmetricKey.xor(src, 0x11); assertArrayEquals(new byte[]{0x11, (byte) 0x44, (byte) 0xEE}, test); } |
Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; } | @Test public void divideAndRemainder() throws Exception { Decimal x = new Decimal("1000000000000"); Decimal[] dr = x.divideAndRemainder(new Decimal(3)); assertEquals("333333333333", dr[0].toString()); assertEquals(1, dr[1].intValue()); } |
Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; } | @Test public void ulp() throws Exception { Decimal x = new Decimal("1000000000000.0000000000000000001"); assertEquals( 1e-19,x.ulp().doubleValue(), 0); } |
SimpleRole extends Role { public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | @Test public void testCloneAsAddressRole() throws Exception { Set<KeyAddress> keyAddresses = new HashSet<>(); keyAddresses.add(new KeyAddress(keys.get(0).getPublicKey(), 0, true)); SimpleRole sr = new SimpleRole("tr1",null, keyAddresses); SimpleRole r1 = sr.cloneAs("tr2",null); SimpleRole r2 = r1.cloneAs("tr1",null); assertEquals(sr, r2); } |
RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } | @Test public void getPublicKey() throws Exception { AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); assertTrue(randomPublicKey4096 instanceof RSAOAEPPublicKey); AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); } |
SimpleRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(keys.get(0).getPublicKey().getShortAddress()); SimpleRole sr = new SimpleRole("tr1",null, keyAddresses); assertEquals(sr.getSimpleAddress(),keyAddresses.iterator().next()); keyAddresses.add(keys.get(1).getPublicKey()); sr = new SimpleRole("tr1", null, keyAddresses); assertNull(sr.getSimpleAddress()); keyAddresses.remove(keys.get(0).getPublicKey().getShortAddress()); sr = new SimpleRole("tr1", null, keyAddresses); assertEquals(sr.getSimpleAddress(),keys.get(1).getPublicKey().getShortAddress()); sr.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(sr.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(sr),keys.get(1).getPublicKey().getShortAddress()); } |
RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | @Test public void resolve() throws Exception { Contract c = new Contract(); SimpleRole s1 = new SimpleRole("owner",c); c.addRole(s1); RoleLink r1 = new RoleLink("lover",c, "owner"); c.addRole(r1); RoleLink r2 = r1.linkAs("mucker"); assertSame(s1, s1.resolve()); assertSame(s1, r1.resolve()); assertSame(s1, r2.resolve()); }
@Test public void detectsCirculars() throws Exception { Contract c = new Contract(); RoleLink r1 = new RoleLink("bar", "foo"); RoleLink r2 = new RoleLink("foo", "bar"); c.registerRole(r1); c.registerRole(r2); assertNull(r2.resolve()); } |
RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | @Test public void serialize() throws Exception { RoleLink r1 = new RoleLink("name", "target"); r1.addRequiredReference("ref", Role.RequiredMode.ALL_OF); Binder s = DefaultBiMapper.serialize(r1); RoleLink r2 = DefaultBiMapper.deserialize(s); assertEquals(r1, r2); assertEquals(r1.getName(), r2.getName()); } |
RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); Contract c = new Contract(); SimpleRole sr = new SimpleRole("sr",c, keyAddresses); c.addRole(sr); RoleLink rl = new RoleLink("rl",c,sr.getName()); c.addRole(rl); assertEquals(rl.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); rl.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(rl.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(rl),TestKeys.publicKey(0).getLongAddress()); } |
ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | @Test public void shouldNotAllowToSetQuorum() { ListRole listRole = new ListRole("roles"); try { listRole.setMode(ListRole.Mode.QUORUM); fail("Expected exception to be thrown."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equalsIgnoreCase("Only ANY or ALL of the modes should be set.")); } } |
ListRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreRefs); } return null; } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); SimpleRole sr = new SimpleRole("sr", keyAddresses); ListRole lr = new ListRole(); lr.addRole(sr); lr.setMode(ListRole.Mode.ALL); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setMode(ListRole.Mode.ANY); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setQuorum(2); assertNull(lr.getSimpleAddress()); lr.setQuorum(1); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setMode(ListRole.Mode.ANY); SimpleRole sr2 = new SimpleRole("sr2", keyAddresses); lr.addRole(sr2); assertNull(lr.getSimpleAddress()); lr.getRoles().remove(sr2); lr.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(lr.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(lr),TestKeys.publicKey(0).getLongAddress()); } |
TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; } | @Test public void deserializeOldContract() throws Exception { TransactionPack tp = TransactionPack.unpack(c.sealAsV2()); checkSimplePack(tp); } |
TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; } | @Test public void serializeNew() throws Exception { TransactionPack tp = new TransactionPack(); tp.setContract(c); checkSimplePack(tp); } |
ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | @Test public void badRevoke() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.seal(); PrivateKey issuer = TestKeys.privateKey(2); Contract tc = c.createRevocation(issuer); boolean result = tc.check(); assertFalse(result); assertEquals(1, tc.getErrors().size()); assertEquals(Errors.FORBIDDEN, tc.getErrors().get(0).getError()); }
@Test public void goodRevoke() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); c.setOwnerKeys(new KeyRecord(goodKey.getPublicKey())); c.seal(); Contract revokeContract = c.createRevocation(goodKey); revokeContract.check(); assertTrue(revokeContract.isOk()); } |
RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } | @Test public void sign() throws Exception { AbstractPrivateKey rsaPrivateKey = pssSpec.getPrivateKey(); assertArrayEquals(rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), pssSpec.S); } |
ContractsService { public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(60)); Binder data = new Binder(); data.set("name", "Default notary"); data.set("description", "Default notary description."); data.set("template_name", "NOTARY_CONTRACT"); data.set("holder_identifier", "default holder identifier"); cd.setData(data); SimpleRole issuerRole = new SimpleRole("issuer",notaryContract); for (PrivateKey k : issuerKeys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); } SimpleRole ownerRole = new SimpleRole("owner",notaryContract); for (PublicKey k : ownerKeys) { KeyRecord kr = new KeyRecord(k); ownerRole.addKeyRecord(kr); } notaryContract.addRole(issuerRole); notaryContract.addRole("issuer", issuerRole); notaryContract.addRole("creator", issuerRole); notaryContract.addRole(ownerRole); notaryContract.addRole("owner", ownerRole); ChangeOwnerPermission changeOwnerPerm = new ChangeOwnerPermission(ownerRole); notaryContract.addPermission(changeOwnerPerm); RevokePermission revokePerm1 = new RevokePermission(ownerRole); notaryContract.addPermission(revokePerm1); RevokePermission revokePerm2 = new RevokePermission(issuerRole); notaryContract.addPermission(revokePerm2); notaryContract.seal(); notaryContract.addSignatureToSeal(issuerKeys); return notaryContract; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | @Test public void goodNotary() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey"))); for (PrivateKey pk : stepaPrivateKeys) stepaPublicKeys.add(pk.getPublicKey()); for (PrivateKey pk : martyPrivateKeys) martyPublicKeys.add(pk.getPublicKey()); Contract notaryContract = ContractsService.createNotaryContract(martyPrivateKeys, stepaPublicKeys); notaryContract.check(); notaryContract.traceErrors(); assertTrue(notaryContract.isOk()); assertTrue(notaryContract.getOwner().isAllowedForKeys(stepaPublicKeys)); assertTrue(notaryContract.getIssuer().isAllowedForKeys(martyPrivateKeys)); assertTrue(notaryContract.getCreator().isAllowedForKeys(martyPrivateKeys)); assertFalse(notaryContract.getOwner().isAllowedForKeys(martyPrivateKeys)); assertFalse(notaryContract.getIssuer().isAllowedForKeys(stepaPublicKeys)); assertFalse(notaryContract.getCreator().isAllowedForKeys(stepaPublicKeys)); assertTrue(notaryContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(notaryContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertTrue(notaryContract.isPermitted("revoke", stepaPublicKeys)); assertTrue(notaryContract.isPermitted("revoke", martyPublicKeys)); assertTrue(notaryContract.isPermitted("change_owner", stepaPublicKeys)); assertFalse(notaryContract.isPermitted("change_owner", martyPublicKeys)); } |
ContractsService { @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minValue), currency, name, description); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | @Test public void goodToken() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey"))); for (PrivateKey pk : stepaPrivateKeys) stepaPublicKeys.add(pk.getPublicKey()); for (PrivateKey pk : martyPrivateKeys) martyPublicKeys.add(pk.getPublicKey()); Contract tokenContract = ContractsService.createTokenContract(martyPrivateKeys, stepaPublicKeys, new BigDecimal("100")); tokenContract.check(); tokenContract.traceErrors(); assertTrue(tokenContract.isOk()); assertTrue(tokenContract.getOwner().isAllowedForKeys(stepaPublicKeys)); assertTrue(tokenContract.getIssuer().isAllowedForKeys(martyPrivateKeys)); assertTrue(tokenContract.getCreator().isAllowedForKeys(martyPrivateKeys)); assertFalse(tokenContract.getOwner().isAllowedForKeys(martyPrivateKeys)); assertFalse(tokenContract.getIssuer().isAllowedForKeys(stepaPublicKeys)); assertFalse(tokenContract.getCreator().isAllowedForKeys(stepaPublicKeys)); assertTrue(tokenContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(tokenContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(tokenContract, "amount"), new Decimal(100)); assertEquals(tokenContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = tokenContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), "0.01"); assertEquals(splitJoinParams.get("min_unit"), "0.01"); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List)splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(tokenContract.isPermitted("revoke", stepaPublicKeys)); assertTrue(tokenContract.isPermitted("revoke", martyPublicKeys)); assertTrue(tokenContract.isPermitted("change_owner", stepaPublicKeys)); assertFalse(tokenContract.isPermitted("change_owner", martyPublicKeys)); assertTrue(tokenContract.isPermitted("split_join", stepaPublicKeys)); assertFalse(tokenContract.isPermitted("split_join", martyPublicKeys)); } |
ContractsService { @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | @Test public void goodShare() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey"))); for (PrivateKey pk : stepaPrivateKeys) stepaPublicKeys.add(pk.getPublicKey()); for (PrivateKey pk : martyPrivateKeys) martyPublicKeys.add(pk.getPublicKey()); Contract shareContract = ContractsService.createShareContract(martyPrivateKeys, stepaPublicKeys, new BigDecimal("100")); shareContract.check(); shareContract.traceErrors(); assertTrue(shareContract.isOk()); assertTrue(shareContract.getOwner().isAllowedForKeys(stepaPublicKeys)); assertTrue(shareContract.getIssuer().isAllowedForKeys(martyPrivateKeys)); assertTrue(shareContract.getCreator().isAllowedForKeys(martyPrivateKeys)); assertFalse(shareContract.getOwner().isAllowedForKeys(martyPrivateKeys)); assertFalse(shareContract.getIssuer().isAllowedForKeys(stepaPublicKeys)); assertFalse(shareContract.getCreator().isAllowedForKeys(stepaPublicKeys)); assertTrue(shareContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(shareContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(shareContract, "amount"), new Decimal(100)); assertEquals(shareContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = shareContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), 1); assertEquals(splitJoinParams.get("min_unit"), 1); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List)splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(shareContract.isPermitted("revoke", stepaPublicKeys)); assertTrue(shareContract.isPermitted("revoke", martyPublicKeys)); assertTrue(shareContract.isPermitted("change_owner", stepaPublicKeys)); assertFalse(shareContract.isPermitted("change_owner", martyPublicKeys)); assertTrue(shareContract.isPermitted("split_join", stepaPublicKeys)); assertFalse(shareContract.isPermitted("split_join", martyPublicKeys)); } |
SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } | @Test public void shouldNotSplitWithWrongDataAmountSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); Binder data = (Binder) state.get("data"); assertNotNull(data); assertTrue(data.size() > 0); data.remove(FIELD_NAME); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); }
@Test public void shouldNotSplitWithWrongCreatedBySerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); state.set("createdBy", "other"); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.set("createdBy", "owner"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); state.remove("createdBy"); Contract dc4 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc4, false); }
@Test public void shouldNotSplitWithWrongOriginSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); HashId origin = HashId.withDigest(Do.randomNegativeBytes(64)); Binder originB = DefaultBiMapper.serialize(origin); state.set("origin", originB); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.remove("origin"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); }
@Test public void shouldNotSplitWithWrongParentSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); HashId parent = HashId.withDigest(Do.randomNegativeBytes(64)); Binder parentB = DefaultBiMapper.serialize(parent); state.set("parent", parentB); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.remove("parent"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); } |
ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } | @Test public void modifyDataAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("field_to_be_changed", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value2"); changed.seal(); changed.check(); assertTrue(changed.isOk()); }
@Test public void modifyDataWhiteList() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("field_to_be_changed", Do.listOf("value2", "value3")); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value2"); changed.seal(); changed.check(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value3"); changed.seal(); changed.check(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value4"); changed.seal(); changed.check(); assertTrue(!changed.isOk()); }
@Test public void modifyExpiresAtAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("/expires_at", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(ZonedDateTime.now().plusDays(1)); changed.seal(); changed.check(); assertTrue(changed.isOk()); }
@Test public void modifyExpiresAtDeclined() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("expires_at", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(ZonedDateTime.now().plusDays(1)); changed.seal(); changed.check(); assertTrue(!changed.isOk()); }
@Test public void modifyExpiresAtWhiteList() throws Exception { ZonedDateTime now = ZonedDateTime.ofInstant(Instant.ofEpochSecond(ZonedDateTime.now().toEpochSecond()), ZoneId.systemDefault()); Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("/expires_at", Do.listOf(now.plusDays(1), now.plusDays(2))); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(now.plusDays(1)); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(now.plusDays(2)); changed.seal(); changed.check(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(now.plusDays(3)); changed.seal(); changed.check(); assertTrue(!changed.isOk()); }
@Test public void modifyReferencesAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"),new Binder()); modifyDataPermission.addField("/references", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract referencedContract = new Contract(TestKeys.privateKey(1)); referencedContract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); Reference ref = new Reference(referencedContract); ref.type = Reference.TYPE_EXISTING_STATE; ref.addMatchingItem(referencedContract); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); }
@Test public void modifyReferencesDeclined() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"),new Binder()); modifyDataPermission.addField("references", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract referencedContract = new Contract(TestKeys.privateKey(1)); referencedContract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); Reference ref = new Reference(referencedContract); ref.addMatchingItem(referencedContract); ref.type = Reference.TYPE_EXISTING_STATE; changed.addReference(ref); changed.seal(); changed.check(); assertTrue(!changed.isOk()); }
@Test public void modifyReferencesWhiteList() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getDefinition().getData().put("type","Good Bank"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"),new Binder()); Contract referencedContract = new Contract(TestKeys.privateKey(1)); referencedContract.seal(); List<String> listConditionsForDefinition = new ArrayList<>(); listConditionsForDefinition.add("ref.definition.data.type == \"Good Bank\""); Binder conditionsForDefinition = new Binder(); conditionsForDefinition.set("all_of", listConditionsForDefinition); Reference ref = new Reference(referencedContract); ref.name = "bank_certificate"; ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(conditionsForDefinition); modifyDataPermission.addField("/references", Do.listOf(ref)); contract.addPermission(modifyDataPermission); contract.seal(); ref = Boss.load(Boss.dump(ref)); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); ref.name = "stepa_certificate"; changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); ref.name = "bank_certificate"; ref.type = Reference.TYPE_TRANSACTIONAL; changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); ref.type = Reference.TYPE_EXISTING_STATE; conditionsForDefinition = new Binder(); conditionsForDefinition.set("any_of", listConditionsForDefinition); ref.setConditions(conditionsForDefinition); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); listConditionsForDefinition = new ArrayList<>(); listConditionsForDefinition.add("ref.definition.data.type == \"Stepa Bank\""); conditionsForDefinition = new Binder(); conditionsForDefinition.set("all_of", listConditionsForDefinition); ref.setConditions(conditionsForDefinition); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); listConditionsForDefinition = new ArrayList<>(); listConditionsForDefinition.add("ref.definition.data.type == \"Good Bank\""); conditionsForDefinition = new Binder(); conditionsForDefinition.set("all_of", listConditionsForDefinition); ref.setConditions(conditionsForDefinition); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); }
@Test public void modifyStatDataAtWhiteList() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("value", Do.listOf("0", "1")); contract.addPermission(modifyDataPermission); contract.getStateData().set("value", null); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("value", "2"); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("value", "1"); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("value", "2"); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); changed.getErrors().clear(); changed.getStateData().set("value", "1"); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); Contract trickContract = new Contract(TestKeys.privateKey(0)); trickContract.addPermission(modifyDataPermission); trickContract.getStateData().set("value", "2"); trickContract.seal(); trickContract.check(); trickContract.traceErrors(); assertTrue(trickContract.isOk()); } |
RSAOAEPPrivateKey extends AbstractPrivateKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } | @Test public void toHash() throws Exception { AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); Map mapRSA = rsaPrivateKey.toHash(); assertArrayEquals((byte[]) mapRSA.get("e"), oaepSpec.e); assertArrayEquals((byte[]) mapRSA.get("p"), oaepSpec.p); assertArrayEquals((byte[]) mapRSA.get("q"), oaepSpec.q); assertFalse(mapRSA.containsKey("mgf1Hash")); AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); Map mapPrivate4096 = randomPrivateKey4096.toHash(), mapPublic4096 = randomPublicKey4096.toHash(); RSAPrivateCrtKeyParameters privateKeyParameters4096 = ((RSAOAEPPrivateKey) randomPrivateKey4096).state.keyParameters; RSAKeyParameters publicKeyParameters4096 = ((RSAOAEPPublicKey) (randomPrivateKey4096.getPublicKey())).state.keyParameters; assertArrayEquals( (byte[]) mapPrivate4096.get("e"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getPublicExponent())); assertArrayEquals( (byte[]) mapPrivate4096.get("p"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getP())); assertArrayEquals( (byte[]) mapPrivate4096.get("q"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getQ())); assertEquals(mapPrivate4096.get("mgf1Hash"), "SHA-512"); assertArrayEquals( (byte[]) mapPublic4096.get("n"), BigIntegers.asUnsignedByteArray(publicKeyParameters4096.getModulus())); assertArrayEquals( (byte[]) mapPublic4096.get("e"), BigIntegers.asUnsignedByteArray(publicKeyParameters4096.getExponent())); assertEquals(mapPublic4096.get("mgf1Hash"), "SHA-512"); } |
Permission implements BiSerializable, Comparable<Permission> { public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } protected Permission(); protected Permission(String name, Role role); protected Permission(String name, Role role, Binder params); @Nullable String getId(); void setId(@NonNull String id); Binder getParams(); static Permission forName(String name, Role role, Binder params); @Deprecated boolean isAllowedForKeys(PublicKey... keys); @Deprecated boolean isAllowedForKeys(Collection<PublicKey> keys); @Deprecated boolean isAllowedFor(Collection<PublicKey> keys); boolean isAllowedForKeysQuantized(PublicKey... keys); boolean isAllowedForKeysQuantized(Collection<PublicKey> keys); boolean isAllowedForQuantized(Collection<PublicKey> keys); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); final void checkChanges(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); abstract void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); @Override String toString(); Role getRole(); String getName(); @Override boolean equals(Object obj); @Override int compareTo(Permission o); } | @Test public void contractGetPermission() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); Contract contract2 = new Contract(TestKeys.privateKey(0)); ChangeNumberPermission changeNumberPermission = new ChangeNumberPermission(new RoleLink("@owner", "owner"), Binder.of( "field_name", "field1", "min_value", 33, "max_value", 34, "min_step", 1, "max_step", 1 ) ); changeNumberPermission.setId("changenumber"); contract.addPermission(changeNumberPermission); contract2.addPermission(changeNumberPermission); contract.seal(); contract2.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction()); contract2 = Contract.fromPackedTransaction(contract2.getPackedTransaction()); assertNotNull(contract.get("definition.permissions.changenumber")); assertEquals((Permission)contract.get("definition.permissions.changenumber"),contract2.get("definition.permissions.changenumber")); } |
ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } | @Test public void sign() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); }
@Test public void parallelExecutionSign() throws Exception { ExecutorService single = Executors.newSingleThreadExecutor(); ExecutorService multiple = Executors.newCachedThreadPool(); byte[] data = "Hello world".getBytes(); PrivateKey k = new PrivateKey(2048); for(int i=0; i<200; i++) ExtendedSignature.sign(k, data); double t1 = parallelize(single, 1, ()-> { for(int i=0; i<100; i++) ExtendedSignature.sign(k, data); }); System.out.println(t1); double t2 = parallelize(multiple, 4, ()-> { for(int i=0; i<100; i++) ExtendedSignature.sign(k, data); }); System.out.println(t2); assertThat(Math.abs(t1-t2), is(lessThan(0.15))); } |
UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } | @Test public void testFromUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = UnikeyFactory.rsaOaepPKFromUnikey(pk1Bytes); assertNotNull(pk1); assertArrayEquals( pk1E, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getPublicExponent())); assertArrayEquals( pk1P, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getP())); assertArrayEquals( pk1Q, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getQ())); } |
ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } | @Test public void extractPublicKey() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); assertNotNull(es.getPublicKey()); assertEquals(pubKey, es.getPublicKey()); } |
Contract implements Approvable, BiSerializable, Cloneable { public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithDsl(binder); } } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } | @Test public void fromYamlFile() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); assertProperSimpleRootContract(c); } |
Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } | @Test public void calculateProcessingCostSimpleBreak() throws Exception { Contract contract = createCoin100apiv3(); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(contract, true); int costShouldBe = 28; boolean exceptionThrown = false; try { processContractAsItWillBeOnTheNode(contract, 10); } catch (Quantiser.QuantiserException e) { System.out.println("Thrown correct exception: " + e.toString()); exceptionThrown = true; } assertEquals(true, exceptionThrown); }
@Test public void calculateProcessingCostSimpleBreakWhileUnpacking() throws Exception { Contract contract = createCoin100apiv3(); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(contract, true); int costShouldBe = 28; boolean exceptionThrown = false; try { processContractAsItWillBeOnTheNode(contract, 1); } catch (Quantiser.QuantiserException e) { System.out.println("Thrown correct exception: " + e.getMessage()); exceptionThrown = true; } catch (BiSerializationException e) { System.out.println("Thrown correct exception: " + e.getMessage()); exceptionThrown = true; } assertEquals(true, exceptionThrown); } |
Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } | @Test public void calculateSplit7To2ProcessingCost_key2048() throws Exception { Contract processingContract = calculateSplit7To2ProcessingCost(PRIVATE_KEY2048_PATH, true); int costShouldBeForSplit = 188; assertEquals(costShouldBeForSplit, processingContract.getProcessedCost()); }
@Test public void calculateSplit7To2ProcessingCost_key4096() throws Exception { Contract processingContract = calculateSplit7To2ProcessingCost(PRIVATE_KEY_PATH, false); int costShouldBeForSplit = 209; assertEquals(costShouldBeForSplit, processingContract.getProcessedCost()); } |
Main { private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resyncBreak = (int) Math.ceil(n * 0.2); if (resyncBreak < 1) resyncBreak = 1; if( resyncBreak+positive == n) resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); config.setResyncBreakConsensus(resyncBreak); }); network = new NetworkV2(netConfig, myInfo, nodeKey); node = new Node(config, myInfo, ledger, network, nodeKey,new File(configRoot+"/config/contracts")); cache = node.getCache(); parcelCache = node.getParcelCache(); paidOperationCache = node.getPaidOperationCache(); envCache = node.getEnvCache(); StateRecord r = ledger.getRecord(HashId.withDigest("bS/c4YMidaVuzTBhHLkGPFAvPbZQHybzQnXAoBwaZYM8eLYb7mAkVYEpuqKRXYc7anqX47BeNdvFN1n7KluH9A==")); if( r != null ) r.destroy(); clientHTTPServer.setConfig(config); clientHTTPServer.setNode(node); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setPaidOperationCache(paidOperationCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost")); } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } | @Test public void startNode() throws Exception { String path = new File("src/test_node_config_v2/node1").getAbsolutePath(); System.out.println(path); String[] args = new String[]{"--test", "--config", path, "--nolog"}; Main main = new Main(args); main.waitReady(); BufferedLogger l = main.logger; Client client = new Client( "http: TestKeys.privateKey(3), main.getNodePublicKey(), null ); Binder data = client.command("status"); data.getStringOrThrow("status"); BasicHttpClient.Answer a = client.request("ping"); assertEquals("200: {ping=pong}", a.toString()); Contract c = new Contract(); c.setIssuerKeys(TestKeys.publicKey(3)); c.addSignerKey(TestKeys.privateKey(3)); c.registerRole(new RoleLink("owner", "issuer")); c.registerRole(new RoleLink("creator", "issuer")); c.setExpiresAt(ZonedDateTime.now().plusDays(2)); byte[] sealed = c.seal(); Contract c1 = new Contract(sealed); assertArrayEquals(c.getLastSealedBinary(), c1.getLastSealedBinary()); main.cache.put(c, null); assertNotNull(main.cache.get(c.getId())); URL url = new URL("http: HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); assertEquals(200, con.getResponseCode()); byte[] data2 = Do.read(con.getInputStream()); assertArrayEquals(c.getPackedTransaction(), data2); url = new URL("http: con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); assertEquals(200, con.getResponseCode()); Binder bres = Boss.unpack((Do.read(con.getInputStream()))) .getBinderOrThrow("response"); List<Binder> ni = bres.getBinders("nodes"); String pubUrls = ni.stream().map(x -> x.getStringOrThrow("url")) .collect(Collectors.toList()) .toString(); assertEquals("[http: main.shutdown(); main.logger.stopInterceptingStdOut(); main.logger.getCopy().forEach(x -> System.out.println(x)); } |
UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } | @Test public void testToUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = new RSAOAEPPrivateKey( pk1E, pk1P, pk1Q, HashType.SHA1, HashType.SHA1, new SecureRandom()); assertArrayEquals( pk1Bytes, UnikeyFactory.toUnikey(pk1)); } |
RSAOAEPDigestFactory { @Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { return null; } } } @Nullable static Digest getDigestByName(String digestName); static Digest cloneDigest(Digest digest); } | @Test public void getDigestByName() throws Exception { Digest dNoDigest1 = RSAOAEPDigestFactory.getDigestByName(""); assertNull(dNoDigest1); Digest dNoDigest2 = RSAOAEPDigestFactory.getDigestByName("Missing hash"); assertNull(dNoDigest2); Digest dSHA1 = RSAOAEPDigestFactory.getDigestByName("SHA-1"); assertArrayEquals( resetAndDigest(dSHA1, "".getBytes()), Hex.decode("da39a3ee5e6b4b0d3255bfef95601890afd80709")); assertArrayEquals( resetAndDigest(dSHA1, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12")); Digest dSHA224 = RSAOAEPDigestFactory.getDigestByName("SHA-224"); assertArrayEquals( resetAndDigest(dSHA224, "".getBytes()), Hex.decode("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")); assertArrayEquals( resetAndDigest(dSHA224, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525")); Digest dSHA256 = RSAOAEPDigestFactory.getDigestByName("SHA-256"); assertArrayEquals( resetAndDigest(dSHA256, "".getBytes()), Hex.decode("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); assertArrayEquals( resetAndDigest(dSHA256, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592")); Digest dSHA384 = RSAOAEPDigestFactory.getDigestByName("SHA-384"); assertArrayEquals( resetAndDigest(dSHA384, "".getBytes()), Hex.decode("38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b")); assertArrayEquals( resetAndDigest(dSHA384, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1")); Digest dSHA512 = RSAOAEPDigestFactory.getDigestByName("SHA-512"); assertArrayEquals( resetAndDigest(dSHA512, "".getBytes()), Hex.decode("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")); assertArrayEquals( resetAndDigest(dSHA512, "The quick brown fox jumps over the lazy dog".getBytes()), Hex.decode("07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6")); } |