repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import java.util.Collection; import java.util.List; /** * Date: 12/27/15 - 12:07 PM * * @author Jeroen Meulemeester */ class OrcsTest extends ObserverTest<GenOrcs> { @Override public Collection<Object[]> dataProvider() { return List.of( new Object[]{WeatherType.SUNNY, "The orcs are facing Sunny weather now"}, new Object[]{WeatherType.RAINY, "The orcs are facing Rainy weather now"}, new Object[]{WeatherType.WINDY, "The orcs are facing Windy weather now"}, new Object[]{WeatherType.COLD, "The orcs are facing Cold weather now"} ); } /** * Create a new test with the given weather and expected response */ public OrcsTest() { super(GenOrcs::new); } }
2,088
36.303571
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import com.iluwatar.observer.WeatherObserver; import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Date: 12/27/15 - 11:08 AM * * @author Jeroen Meulemeester */ class GWeatherTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(GenWeather.class); } @AfterEach void tearDown() { appender.stop(); } /** * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the * observer again and verify that there are no more notifications. */ @Test void testAddRemoveObserver() { final var observer = mock(Race.class); final var weather = new GenWeather(); weather.addObserver(observer); verifyNoMoreInteractions(observer); weather.timePasses(); assertEquals("The weather changed to rainy.", appender.getLastMessage()); verify(observer).update(weather, WeatherType.RAINY); weather.removeObserver(observer); weather.timePasses(); assertEquals("The weather changed to windy.", appender.getLastMessage()); verifyNoMoreInteractions(observer); assertEquals(2, appender.getLogSize()); } /** * Verify if the weather passes in the order of the {@link WeatherType}s */ @Test void testTimePasses() { final var observer = mock(Race.class); final var weather = new GenWeather(); weather.addObserver(observer); final var inOrder = inOrder(observer); final var weatherTypes = WeatherType.values(); for (var i = 1; i < 20; i++) { weather.timePasses(); inOrder.verify(observer).update(weather, weatherTypes[i % weatherTypes.length]); } verifyNoMoreInteractions(observer); } }
3,423
32.242718
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import java.util.Collection; import java.util.List; /** * Date: 12/27/15 - 12:07 PM * * @author Jeroen Meulemeester */ class GHobbitsTest extends ObserverTest<GenHobbits> { @Override public Collection<Object[]> dataProvider() { return List.of( new Object[]{WeatherType.SUNNY, "The hobbits are facing Sunny weather now"}, new Object[]{WeatherType.RAINY, "The hobbits are facing Rainy weather now"}, new Object[]{WeatherType.WINDY, "The hobbits are facing Windy weather now"}, new Object[]{WeatherType.COLD, "The hobbits are facing Cold weather now"} ); } /** * Create a new test with the given weather and expected response */ public GHobbitsTest() { super(GenHobbits::new); } }
2,114
36.767857
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.utils.InMemoryAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.Collection; import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Date: 12/27/15 - 11:44 AM * Test for Observers * @param <O> Type of Observer * @author Jeroen Meulemeester */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class ObserverTest<O extends Observer<?, ?, WeatherType>> { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } /** * The observer instance factory */ private final Supplier<O> factory; /** * Create a new test instance using the given parameters * * @param factory The factory, used to create an instance of the tested observer */ ObserverTest(final Supplier<O> factory) { this.factory = factory; } public abstract Collection<Object[]> dataProvider(); /** * Verify if the weather has the expected influence on the observer */ @ParameterizedTest @MethodSource("dataProvider") void testObserver(WeatherType weather, String response) { final var observer = this.factory.get(); assertEquals(0, appender.getLogSize()); observer.update(null, weather); assertEquals(response, appender.getLastMessage()); assertEquals(1, appender.getLogSize()); } }
3,001
31.630435
140
java
java-design-patterns
java-design-patterns-master/observer/src/test/java/com/iluwatar/observer/utils/InMemoryAppender.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.List; /** * InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public int getLogSize() { return log.size(); } public String getLastMessage() { return log.get(log.size() - 1).getFormattedMessage(); } }
2,194
33.84127
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/WeatherObserver.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; /** * Observer interface. */ public interface WeatherObserver { void update(WeatherType currentWeather); }
1,429
39.857143
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import com.iluwatar.observer.generic.GenHobbits; import com.iluwatar.observer.generic.GenOrcs; import com.iluwatar.observer.generic.GenWeather; import lombok.extern.slf4j.Slf4j; /** * The Observer pattern is a software design pattern in which an object, called the subject, * maintains a list of its dependents, called observers, and notifies them automatically of any * state changes, usually by calling one of their methods. It is mainly used to implement * distributed event handling systems. The Observer pattern is also a key part in the familiar * model–view–controller (MVC) architectural pattern. The Observer pattern is implemented in * numerous programming libraries and systems, including almost all GUI toolkits. * * <p>In this example {@link Weather} has a state that can be observed. The {@link Orcs} and {@link * Hobbits} register as observers and receive notifications when the {@link Weather} changes. */ @Slf4j public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { var weather = new Weather(); weather.addObserver(new Orcs()); weather.addObserver(new Hobbits()); weather.timePasses(); weather.timePasses(); weather.timePasses(); weather.timePasses(); // Generic observer inspired by Java Generics and Collections by Naftalin & Wadler LOGGER.info("--Running generic version--"); var genericWeather = new GenWeather(); genericWeather.addObserver(new GenOrcs()); genericWeather.addObserver(new GenHobbits()); genericWeather.timePasses(); genericWeather.timePasses(); genericWeather.timePasses(); genericWeather.timePasses(); } }
3,028
39.932432
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/WeatherType.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; /** * WeatherType enumeration. */ public enum WeatherType { SUNNY("Sunny"), RAINY("Rainy"), WINDY("Windy"), COLD("Cold"); private final String description; WeatherType(String description) { this.description = description; } public String getDescription() { return this.description; } @Override public String toString() { return this.name().toLowerCase(); } }
1,718
32.057692
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/Orcs.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import lombok.extern.slf4j.Slf4j; /** * Orcs. */ @Slf4j public class Orcs implements WeatherObserver { @Override public void update(WeatherType currentWeather) { LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now"); } }
1,584
38.625
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/Hobbits.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import lombok.extern.slf4j.Slf4j; /** * Hobbits. */ @Slf4j public class Hobbits implements WeatherObserver { @Override public void update(WeatherType currentWeather) { LOGGER.info("The hobbits are facing {} weather now", currentWeather.getDescription()); } }
1,589
38.75
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/Weather.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; /** * Weather can be observed by implementing {@link WeatherObserver} interface and registering as * listener. */ @Slf4j public class Weather { private WeatherType currentWeather; private final List<WeatherObserver> observers; public Weather() { observers = new ArrayList<>(); currentWeather = WeatherType.SUNNY; } public void addObserver(WeatherObserver obs) { observers.add(obs); } public void removeObserver(WeatherObserver obs) { observers.remove(obs); } /** * Makes time pass for weather. */ public void timePasses() { var enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(); } private void notifyObservers() { for (var obs : observers) { obs.update(currentWeather); } } }
2,308
31.985714
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/generic/GenHobbits.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import lombok.extern.slf4j.Slf4j; /** * GHobbits. */ @Slf4j public class GenHobbits implements Race { @Override public void update(GenWeather weather, WeatherType weatherType) { LOGGER.info("The hobbits are facing " + weatherType.getDescription() + " weather now"); } }
1,650
39.268293
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/generic/Observable.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Generic observer inspired by Java Generics and Collection by {@literal Naftalin & Wadler}. * * @param <S> Subject * @param <O> Observer * @param <A> Argument type */ public abstract class Observable<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> { protected final List<O> observers; public Observable() { this.observers = new CopyOnWriteArrayList<>(); } public void addObserver(O observer) { this.observers.add(observer); } public void removeObserver(O observer) { this.observers.remove(observer); } /** * Notify observers. */ @SuppressWarnings("unchecked") public void notifyObservers(A argument) { for (var observer : observers) { observer.update((S) this, argument); } } }
2,161
33.31746
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/generic/GenOrcs.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import lombok.extern.slf4j.Slf4j; /** * GOrcs. */ @Slf4j public class GenOrcs implements Race { @Override public void update(GenWeather weather, WeatherType weatherType) { LOGGER.info("The orcs are facing " + weatherType.getDescription() + " weather now"); } }
1,641
39.04878
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/generic/GenWeather.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; import lombok.extern.slf4j.Slf4j; /** * GWeather. */ @Slf4j public class GenWeather extends Observable<GenWeather, Race, WeatherType> { private WeatherType currentWeather; public GenWeather() { currentWeather = WeatherType.SUNNY; } /** * Makes time pass for weather. */ public void timePasses() { var enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(currentWeather); } }
1,923
36
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/generic/Race.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; import com.iluwatar.observer.WeatherType; /** * Race. */ public interface Race extends Observer<GenWeather, Race, WeatherType> { }
1,458
41.911765
140
java
java-design-patterns
java-design-patterns-master/observer/src/main/java/com/iluwatar/observer/generic/Observer.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer.generic; /** * Observer. * * @param <S> Observable * @param <O> Observer * @param <A> Action */ public interface Observer<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> { void update(S subject, A argument); }
1,549
39.789474
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/test/java/com/iluwatar/presentationmodel/ViewTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class ViewTest { String[] albumList = {"HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5"}; @Test void testSave_setArtistAndTitle(){ View view = new View(); view.createView(); String testTitle = "testTitle"; String testArtist = "testArtist"; view.getTxtArtist().setText(testArtist); view.getTxtTitle().setText(testTitle); view.saveToMod(); view.loadFromMod(); assertEquals(testTitle, view.getModel().getTitle()); assertEquals(testArtist, view.getModel().getArtist()); } @Test void testSave_setClassicalAndComposer(){ View view = new View(); view.createView(); boolean isClassical = true; String testComposer = "testComposer"; view.getChkClassical().setSelected(isClassical); view.getTxtComposer().setText(testComposer); view.saveToMod(); view.loadFromMod(); assertTrue(view.getModel().getIsClassical()); assertEquals(testComposer, view.getModel().getComposer()); } @Test void testLoad_1(){ View view = new View(); view.createView(); view.getModel().setSelectedAlbumNumber(2); view.loadFromMod(); assertEquals(albumList[1], view.getModel().getTitle()); } @Test void testLoad_2(){ View view = new View(); view.createView(); view.getModel().setSelectedAlbumNumber(4); view.loadFromMod(); assertEquals(albumList[3], view.getModel().getTitle()); } }
2,905
35.325
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/test/java/com/iluwatar/presentationmodel/AlbumTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class AlbumTest { @Test void testSetTitle(){ Album album = new Album("a", "b", false, ""); album.setTitle("b"); assertEquals("b", album.getTitle()); } @Test void testSetArtist(){ Album album = new Album("a", "b", false, ""); album.setArtist("c"); assertEquals("c", album.getArtist()); } @Test void testSetClassical(){ Album album = new Album("a", "b", false, ""); album.setClassical(true); assertTrue(album.isClassical()); } @Test void testSetComposer(){ Album album = new Album("a", "b", false, ""); album.setClassical(true); album.setComposer("w"); assertEquals("w", album.getComposer()); } }
2,156
33.790323
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/test/java/com/iluwatar/presentationmodel/PresentationTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class PresentationTest { String[] albumList = {"HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5"}; @Test void testCreateAlbumList() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String[] list = model.getAlbumList(); assertEquals(Arrays.toString(albumList), Arrays.toString(list)); } @Test void testSetSelectedAlbumNumber_1() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); final int selectId = 2; model.setSelectedAlbumNumber(selectId); assertEquals(albumList[selectId - 1], model.getTitle()); } @Test void testSetSelectedAlbumNumber_2() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); final int selectId = 4; model.setSelectedAlbumNumber(selectId); assertEquals(albumList[selectId - 1], model.getTitle()); } @Test void testSetTitle_1() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String testTitle = "TestTile"; model.setTitle(testTitle); assertEquals(testTitle, model.getTitle()); } @Test void testSetTitle_2() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String testTitle = ""; model.setTitle(testTitle); assertEquals(testTitle, model.getTitle()); } @Test void testSetArtist_1() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String testArtist = "TestArtist"; model.setArtist(testArtist); assertEquals(testArtist, model.getArtist()); } @Test void testSetArtist_2() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String testArtist = ""; model.setArtist(testArtist); assertEquals(testArtist, model.getArtist()); } @Test void testSetIsClassical() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); model.setIsClassical(true); assertTrue(model.getIsClassical()); } @Test void testSetComposer_false() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String testComposer = "TestComposer"; model.setIsClassical(false); model.setComposer(testComposer); assertEquals("", model.getComposer()); } @Test void testSetComposer_true() { PresentationModel model = new PresentationModel(PresentationModel.albumDataSet()); String testComposer = "TestComposer"; model.setIsClassical(true); model.setComposer(testComposer); assertEquals(testComposer, model.getComposer()); } }
4,171
34.058824
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/test/java/com/iluwatar/presentationmodel/DisplayedAlbumsTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class DisplayedAlbumsTest { @Test void testAdd_true(){ DisplayedAlbums displayedAlbums = new DisplayedAlbums(); displayedAlbums.addAlbums("title", "artist", true, "composer"); assertEquals("composer", displayedAlbums.getAlbums().get(0).getComposer()); } @Test void testAdd_false(){ DisplayedAlbums displayedAlbums = new DisplayedAlbums(); displayedAlbums.addAlbums("title", "artist", false, "composer"); assertEquals("", displayedAlbums.getAlbums().get(0).getComposer()); } }
1,937
40.234043
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/test/java/com/iluwatar/presentationmodel/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Issue: Add at least one assertion to this test case. * * Solution: Inserted assertion to check whether the execution of the main method in {@link App} * throws an exception. */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,766
39.159091
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/main/java/com/iluwatar/presentationmodel/Album.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** *A class used to store the information of album. */ @Setter @Getter @AllArgsConstructor public class Album { /** * the title of the album. */ private String title; /** * the artist name of the album. */ private String artist; /** * is the album classical, true or false. */ private boolean isClassical; /** * only when the album is classical, * composer can have content. */ private String composer; }
1,855
32.142857
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/main/java/com/iluwatar/presentationmodel/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import lombok.extern.slf4j.Slf4j; /** * The Presentation model pattern is used to divide the presentation and controlling. * This demo is a used to information of some albums with GUI. */ @Slf4j public final class App { /** * the constructor. */ private App() { } /** * main method. * * @param args args */ public static void main(final String[] args) { var view = new View(); view.createView(); } }
1,769
33.038462
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/main/java/com/iluwatar/presentationmodel/View.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import java.awt.TextField; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JList; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * Generates the GUI of albums. */ @Getter @Slf4j public class View { /** * the model that controls this view. */ private final PresentationModel model; /** * the filed to show and modify title. */ private TextField txtTitle; /** * the filed to show and modify the name of artist. */ private TextField txtArtist; /** * the checkbox for is classical. */ private JCheckBox chkClassical; /** * the filed to show and modify composer. */ private TextField txtComposer; /** * a list to show all the name of album. */ private JList<String> albumList; /** * a button to apply of all the change. */ private JButton apply; /** * roll back the change. */ private JButton cancel; /** * the value of the text field size. */ static final int WIDTH_TXT = 200; static final int HEIGHT_TXT = 50; /** * the value of the GUI size and location. */ static final int LOCATION_X = 200; static final int LOCATION_Y = 200; static final int WIDTH = 500; static final int HEIGHT = 300; /** * constructor method. */ public View() { model = new PresentationModel(PresentationModel.albumDataSet()); } /** * save the data to PresentationModel. */ public void saveToMod() { LOGGER.info("Save data to PresentationModel"); model.setArtist(txtArtist.getText()); model.setTitle(txtTitle.getText()); model.setIsClassical(chkClassical.isSelected()); model.setComposer(txtComposer.getText()); } /** * load the data from PresentationModel. */ public void loadFromMod() { LOGGER.info("Load data from PresentationModel"); txtArtist.setText(model.getArtist()); txtTitle.setText(model.getTitle()); chkClassical.setSelected(model.getIsClassical()); txtComposer.setEditable(model.getIsClassical()); txtComposer.setText(model.getComposer()); } /** * initialize the GUI. */ public void createView() { var frame = new JFrame("Album"); var b1 = Box.createHorizontalBox(); frame.add(b1); albumList = new JList<>(model.getAlbumList()); albumList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { model.setSelectedAlbumNumber(albumList.getSelectedIndex() + 1); loadFromMod(); } }); b1.add(albumList); var b2 = Box.createVerticalBox(); b1.add(b2); txtArtist = new TextField(); txtTitle = new TextField(); txtArtist.setSize(WIDTH_TXT, HEIGHT_TXT); txtTitle.setSize(WIDTH_TXT, HEIGHT_TXT); chkClassical = new JCheckBox(); txtComposer = new TextField(); chkClassical.addActionListener(itemEvent -> { txtComposer.setEditable(chkClassical.isSelected()); if (!chkClassical.isSelected()) { txtComposer.setText(""); } }); txtComposer.setSize(WIDTH_TXT, HEIGHT_TXT); txtComposer.setEditable(model.getIsClassical()); apply = new JButton("Apply"); apply.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { saveToMod(); loadFromMod(); } }); cancel = new JButton("Cancel"); cancel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { loadFromMod(); } }); b2.add(txtArtist); b2.add(txtTitle); b2.add(chkClassical); b2.add(txtComposer); b2.add(apply); b2.add(cancel); frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); frame.setBounds(LOCATION_X, LOCATION_Y, WIDTH, HEIGHT); frame.setVisible(true); } }
5,286
26.680628
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/main/java/com/iluwatar/presentationmodel/PresentationModel.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import lombok.extern.slf4j.Slf4j; /** * The class between view and albums, it is used to control the data. */ @Slf4j public class PresentationModel { /** * the data of all albums that will be shown. */ private final DisplayedAlbums data; /** * the no of selected album. */ private int selectedAlbumNumber; /** * the selected album. */ private Album selectedAlbum; /** * Generates a set of data for testing. * * @return a instance of DsAlbum which store the data. */ public static DisplayedAlbums albumDataSet() { var titleList = new String[]{"HQ", "The Rough Dancer and Cyclical Night", "The Black Light", "Symphony No.5"}; var artistList = new String[]{"Roy Harper", "Astor Piazzola", "The Black Light", "CBSO"}; var isClassicalList = new boolean[]{false, false, false, true}; var composerList = new String[]{null, null, null, "Sibelius"}; var result = new DisplayedAlbums(); for (var i = 1; i <= titleList.length; i++) { result.addAlbums(titleList[i - 1], artistList[i - 1], isClassicalList[i - 1], composerList[i - 1]); } return result; } /** * constructor method. * * @param dataOfAlbums the data of all the albums */ public PresentationModel(final DisplayedAlbums dataOfAlbums) { this.data = dataOfAlbums; this.selectedAlbumNumber = 1; this.selectedAlbum = this.data.getAlbums().get(0); } /** * Changes the value of selectedAlbumNumber. * * @param albumNumber the number of album which is shown on the view. */ public void setSelectedAlbumNumber(final int albumNumber) { LOGGER.info("Change select number from {} to {}", this.selectedAlbumNumber, albumNumber); this.selectedAlbumNumber = albumNumber; this.selectedAlbum = data.getAlbums().get(this.selectedAlbumNumber - 1); } /** * get the title of selected album. * * @return the tile of selected album. */ public String getTitle() { return selectedAlbum.getTitle(); } /** * set the title of selected album. * * @param value the title which user want to user. */ public void setTitle(final String value) { LOGGER.info("Change album title from {} to {}", selectedAlbum.getTitle(), value); selectedAlbum.setTitle(value); } /** * get the artist of selected album. * * @return the artist of selected album. */ public String getArtist() { return selectedAlbum.getArtist(); } /** * set the name of artist. * * @param value the name want artist to be. */ public void setArtist(final String value) { LOGGER.info("Change album artist from {} to {}", selectedAlbum.getArtist(), value); selectedAlbum.setArtist(value); } /** * Gets a boolean value which represents whether the album is classical. * * @return is the album classical. */ public boolean getIsClassical() { return selectedAlbum.isClassical(); } /** * set the isClassical of album. * * @param value is the album classical. */ public void setIsClassical(final boolean value) { LOGGER.info("Change album isClassical from {} to {}", selectedAlbum.isClassical(), value); selectedAlbum.setClassical(value); } /** * get is classical of the selected album. * * @return is the album classical. */ public String getComposer() { return selectedAlbum.isClassical() ? selectedAlbum.getComposer() : ""; } /** * Sets the name of composer when the album is classical. * * @param value the name of composer. */ public void setComposer(final String value) { if (selectedAlbum.isClassical()) { LOGGER.info("Change album composer from {} to {}", selectedAlbum.getComposer(), value); selectedAlbum.setComposer(value); } else { LOGGER.info("Composer can not be changed"); } } /** * Gets a list of albums. * * @return the names of all the albums. */ public String[] getAlbumList() { var result = new String[data.getAlbums().size()]; for (var i = 0; i < result.length; i++) { result[i] = data.getAlbums().get(i).getTitle(); } return result; } }
5,613
28.861702
140
java
java-design-patterns
java-design-patterns-master/presentation-model/src/main/java/com/iluwatar/presentationmodel/DisplayedAlbums.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.presentationmodel; import java.util.ArrayList; import java.util.List; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * a class used to deal with albums. * */ @Slf4j @Getter public class DisplayedAlbums { /** * albums a list of albums. */ private final List<Album> albums; /** * a constructor method. */ public DisplayedAlbums() { this.albums = new ArrayList<>(); } /** * a method used to add a new album to album list. * * @param title the title of the album. * @param artist the artist name of the album. * @param isClassical is the album classical, true or false. * @param composer only when the album is classical, * composer can have content. */ public void addAlbums(final String title, final String artist, final boolean isClassical, final String composer) { if (isClassical) { this.albums.add(new Album(title, artist, true, composer)); } else { this.albums.add(new Album(title, artist, false, "")); } } }
2,398
33.271429
140
java
java-design-patterns
java-design-patterns-master/marker/src/test/java/GuardTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; /** * Guard test */ class GuardTest { @Test void testGuard() { var guard = new Guard(); assertThat(guard, instanceOf(Permission.class)); } }
1,583
38.6
140
java
java-design-patterns
java-design-patterns-master/marker/src/test/java/ThiefTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; /** * Thief test */ class ThiefTest { @Test void testThief() { var thief = new Thief(); assertThat(thief, not(instanceOf(Permission.class))); } }
1,632
39.825
140
java
java-design-patterns
java-design-patterns-master/marker/src/test/java/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,555
38.897436
140
java
java-design-patterns
java-design-patterns-master/marker/src/main/java/Thief.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import lombok.extern.slf4j.Slf4j; /** * Class defining Thief. */ @Slf4j public class Thief { protected void steal() { LOGGER.info("Steal valuable items"); } protected void doNothing() { LOGGER.info("Pretend nothing happened and just leave"); } }
1,551
36.853659
140
java
java-design-patterns
java-design-patterns-master/marker/src/main/java/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Alexis on 28-Apr-17. With Marker interface idea is to make empty interface and extend * it. Basically it is just to identify the special objects from normal objects. Like in case of * serialization , objects that need to be serialized must implement serializable interface (it is * empty interface) and down the line writeObject() method must be checking if it is a instance of * serializable or not. * * <p>Marker interface vs annotation Marker interfaces and marker annotations both have their uses, * neither of them is obsolete or always better then the other one. If you want to define a type * that does not have any new methods associated with it, a marker interface is the way to go. If * you want to mark program elements other than classes and interfaces, to allow for the possibility * of adding more information to the marker in the future, or to fit the marker into a framework * that already makes heavy use of annotation types, then a marker annotation is the correct choice */ public class App { /** * Program entry point. * * @param args command line args */ public static void main(String[] args) { final var logger = LoggerFactory.getLogger(App.class); var guard = new Guard(); var thief = new Thief(); //noinspection ConstantConditions if (guard instanceof Permission) { guard.enter(); } else { logger.info("You have no permission to enter, please leave this area"); } //noinspection ConstantConditions if (thief instanceof Permission) { thief.steal(); } else { thief.doNothing(); } } }
2,969
41.428571
140
java
java-design-patterns
java-design-patterns-master/marker/src/main/java/Permission.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Interface without any methods Marker interface is based on that assumption. */ public interface Permission { }
1,403
45.8
140
java
java-design-patterns
java-design-patterns-master/marker/src/main/java/Guard.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import lombok.extern.slf4j.Slf4j; /** * Class defining Guard. */ @Slf4j public class Guard implements Permission { protected void enter() { LOGGER.info("You can enter"); } }
1,470
38.756757
140
java
java-design-patterns
java-design-patterns-master/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.guarded.suspension; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; /** * Test for Guarded Queue */ class GuardedQueueTest { private volatile Integer value; @Test void testGet() { var g = new GuardedQueue(); var executorService = Executors.newFixedThreadPool(2); executorService.submit(() -> value = g.get()); executorService.submit(() -> g.put(10)); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(Integer.valueOf(10), value); } @Test void testPut() { var g = new GuardedQueue(); g.put(12); assertEquals(Integer.valueOf(12), g.get()); } }
2,165
33.935484
140
java
java-design-patterns
java-design-patterns-master/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/GuardedQueue.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.guarded.suspension; import java.util.LinkedList; import java.util.Queue; import lombok.extern.slf4j.Slf4j; /** * Guarded Queue is an implementation for Guarded Suspension Pattern Guarded suspension pattern is * used to handle a situation when you want to execute a method on an object which is not in a * proper state. * * @see <a href="http://java-design-patterns.com/patterns/guarded-suspension/">http://java-design-patterns.com/patterns/guarded-suspension/</a> */ @Slf4j public class GuardedQueue { private final Queue<Integer> sourceList; public GuardedQueue() { this.sourceList = new LinkedList<>(); } /** * Get the last element of the queue is exists. * * @return last element of a queue if queue is not empty */ public synchronized Integer get() { while (sourceList.isEmpty()) { try { LOGGER.info("waiting"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } LOGGER.info("getting"); return sourceList.peek(); } /** * Put a value in the queue. * * @param e number which we want to put to our queue */ public synchronized void put(Integer e) { LOGGER.info("putting"); sourceList.add(e); LOGGER.info("notifying"); notify(); } }
2,586
33.039474
143
java
java-design-patterns
java-design-patterns-master/guarded-suspension/src/main/java/com/iluwatar/guarded/suspension/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.guarded.suspension; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Created by robertt240 on 1/26/17. * * <p>Guarded-suspension is a concurrent design pattern for handling situation when to execute some * action we need condition to be satisfied. * * <p>Implementation is based on GuardedQueue, which has two methods: get and put, the condition is * that we cannot get from empty queue so when thread attempt to break the condition we invoke * Object's wait method on him and when other thread put an element to the queue he notify the * waiting one that now he can get from queue. */ public class App { /** * Example pattern execution. * * @param args - command line args */ public static void main(String[] args) { var guardedQueue = new GuardedQueue(); var executorService = Executors.newFixedThreadPool(3); //here we create first thread which is supposed to get from guardedQueue executorService.execute(guardedQueue::get); // here we wait two seconds to show that the thread which is trying // to get from guardedQueue will be waiting try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } // now we execute second thread which will put number to guardedQueue // and notify first thread that it could get executorService.execute(() -> guardedQueue.put(20)); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }
2,905
38.808219
140
java
java-design-patterns
java-design-patterns-master/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.proxy.utils.InMemoryAppender; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for {@link WizardTowerProxy} */ class WizardTowerProxyTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(); } @AfterEach void tearDown() { appender.stop(); } @Test void testEnter() { final var wizards = List.of( new Wizard("Gandalf"), new Wizard("Dumbledore"), new Wizard("Oz"), new Wizard("Merlin") ); final var proxy = new WizardTowerProxy(new IvoryTower()); wizards.forEach(proxy::enter); assertTrue(appender.logContains("Gandalf enters the tower.")); assertTrue(appender.logContains("Dumbledore enters the tower.")); assertTrue(appender.logContains("Oz enters the tower.")); assertTrue(appender.logContains("Merlin is not allowed to enter!")); assertEquals(4, appender.getLogSize()); } }
2,482
33.486111
140
java
java-design-patterns
java-design-patterns-master/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.Test; /** * Tests for {@link Wizard} */ class WizardTest { @Test void testToString() { List.of("Gandalf", "Dumbledore", "Oz", "Merlin") .forEach(name -> assertEquals(name, new Wizard(name).toString())); } }
1,655
38.428571
140
java
java-design-patterns
java-design-patterns-master/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.iluwatar.proxy.utils.InMemoryAppender; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for {@link IvoryTower} */ class IvoryTowerTest { private InMemoryAppender appender; @BeforeEach void setUp() { appender = new InMemoryAppender(IvoryTower.class); } @AfterEach void tearDown() { appender.stop(); } @Test void testEnter() { final var wizards = List.of( new Wizard("Gandalf"), new Wizard("Dumbledore"), new Wizard("Oz"), new Wizard("Merlin") ); var tower = new IvoryTower(); wizards.forEach(tower::enter); assertTrue(appender.logContains("Gandalf enters the tower.")); assertTrue(appender.logContains("Dumbledore enters the tower.")); assertTrue(appender.logContains("Oz enters the tower.")); assertTrue(appender.logContains("Merlin enters the tower.")); assertEquals(4, appender.getLogSize()); } }
2,451
33.055556
140
java
java-design-patterns
java-design-patterns-master/proxy/src/test/java/com/iluwatar/proxy/AppTest.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Application test */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
1,584
37.658537
140
java
java-design-patterns
java-design-patterns-master/proxy/src/test/java/com/iluwatar/proxy/utils/InMemoryAppender.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy.utils; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.LinkedList; import java.util.List; import org.slf4j.LoggerFactory; /** * InMemory Log Appender Util. */ public class InMemoryAppender extends AppenderBase<ILoggingEvent> { private final List<ILoggingEvent> log = new LinkedList<>(); public InMemoryAppender(Class<?> clazz) { ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); start(); } public InMemoryAppender() { ((Logger) LoggerFactory.getLogger("root")).addAppender(this); start(); } @Override protected void append(ILoggingEvent eventObject) { log.add(eventObject); } public boolean logContains(String message) { return log.stream().map(ILoggingEvent::getFormattedMessage).anyMatch(message::equals); } public int getLogSize() { return log.size(); } }
2,240
34.015625
140
java
java-design-patterns
java-design-patterns-master/proxy/src/main/java/com/iluwatar/proxy/App.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; /** * A proxy, in its most general form, is a class functioning as an interface to something else. The * proxy could interface to anything: a network connection, a large object in memory, a file, or * some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper * or agent object that is being called by the client to access the real serving object behind the * scenes. * * <p>The Proxy design pattern allows you to provide an interface to other objects by creating a * wrapper class as the proxy. The wrapper class, which is the proxy, can add additional * functionality to the object of interest without changing the object's code. * * <p>In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object ( * {@link IvoryTower}). */ public class App { /** * Program entry point. */ public static void main(String[] args) { var proxy = new WizardTowerProxy(new IvoryTower()); proxy.enter(new Wizard("Red wizard")); proxy.enter(new Wizard("White wizard")); proxy.enter(new Wizard("Black wizard")); proxy.enter(new Wizard("Green wizard")); proxy.enter(new Wizard("Brown wizard")); } }
2,509
43.035088
140
java
java-design-patterns
java-design-patterns-master/proxy/src/main/java/com/iluwatar/proxy/WizardTowerProxy.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import lombok.extern.slf4j.Slf4j; /** * The proxy controlling access to the {@link IvoryTower}. */ @Slf4j public class WizardTowerProxy implements WizardTower { private static final int NUM_WIZARDS_ALLOWED = 3; private int numWizards; private final WizardTower tower; public WizardTowerProxy(WizardTower tower) { this.tower = tower; } @Override public void enter(Wizard wizard) { if (numWizards < NUM_WIZARDS_ALLOWED) { tower.enter(wizard); numWizards++; } else { LOGGER.info("{} is not allowed to enter!", wizard); } } }
1,893
33.436364
140
java
java-design-patterns
java-design-patterns-master/proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import lombok.extern.slf4j.Slf4j; /** * The object to be proxied. */ @Slf4j public class IvoryTower implements WizardTower { public void enter(Wizard wizard) { LOGGER.info("{} enters the tower.", wizard); } }
1,535
37.4
140
java
java-design-patterns
java-design-patterns-master/proxy/src/main/java/com/iluwatar/proxy/Wizard.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; import lombok.RequiredArgsConstructor; /** * Wizard. */ @RequiredArgsConstructor public class Wizard { private final String name; @Override public String toString() { return name; } }
1,515
34.255814
140
java
java-design-patterns
java-design-patterns-master/proxy/src/main/java/com/iluwatar/proxy/WizardTower.java
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.proxy; /** * WizardTower interface. */ public interface WizardTower { void enter(Wizard wizard); }
1,410
40.5
140
java
java-design-patterns
java-design-patterns-master/component/src/test/java/com/iluwatar/component/GameObjectTest.java
package com.iluwatar.component; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import java.awt.event.KeyEvent; import lombok.extern.slf4j.Slf4j; /** * Tests GameObject class. * src/main/java/com/iluwatar/component/GameObject.java */ @Slf4j class GameObjectTest { GameObject playerTest; GameObject npcTest; @BeforeEach public void initEach() { //creates player & npc objects for testing //note that velocity and coordinates are initialised to 0 in GameObject.java playerTest = GameObject.createPlayer(); npcTest = GameObject.createNpc(); } /** * Tests the create methods - createPlayer() and createNPC(). */ @Test void objectTest(){ LOGGER.info("objectTest:"); assertEquals("player",playerTest.getName()); assertEquals("npc",npcTest.getName()); } /** * Tests the input component with varying key event inputs. * Targets the player game object. */ @Test void eventInputTest(){ LOGGER.info("eventInputTest:"); playerTest.update(KeyEvent.KEY_LOCATION_LEFT); assertEquals(-1, playerTest.getVelocity()); assertEquals(-1, playerTest.getCoordinate()); playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); playerTest.update(KeyEvent.KEY_LOCATION_RIGHT); assertEquals(1, playerTest.getVelocity()); assertEquals(0, playerTest.getCoordinate()); LOGGER.info(Integer.toString(playerTest.getCoordinate())); LOGGER.info(Integer.toString(playerTest.getVelocity())); GameObject p2 = GameObject.createPlayer(); p2.update(KeyEvent.KEY_LOCATION_LEFT); //in the case of an unknown, object stats are set to default p2.update(KeyEvent.KEY_LOCATION_UNKNOWN); assertEquals(-1, p2.getVelocity()); } /** * Tests the demo component interface. */ @Test void npcDemoTest(){ LOGGER.info("npcDemoTest:"); npcTest.demoUpdate(); assertEquals(2, npcTest.getVelocity()); assertEquals(2, npcTest.getCoordinate()); } }
2,187
29.388889
84
java
java-design-patterns
java-design-patterns-master/component/src/test/java/com/iluwatar/component/AppTest.java
package com.iluwatar.component; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * Tests App class : src/main/java/com/iluwatar/component/App.java * General execution test of the application. */ class AppTest { @Test void shouldExecuteComponentWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
405
21.555556
66
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/App.java
package com.iluwatar.component; import java.awt.event.KeyEvent; import lombok.extern.slf4j.Slf4j; /** * The component design pattern is a common game design structure. This pattern is often * used to reduce duplication of code as well as to improve maintainability. * In this implementation, component design pattern has been used to provide two game * objects with varying component interfaces (features). As opposed to copying and * pasting same code for the two game objects, the component interfaces allow game * objects to inherit these components from the component classes. * * <p>The implementation has decoupled graphic, physics and input components from * the player and NPC objects. As a result, it avoids the creation of monolithic java classes. * * <p>The below example in this App class demonstrates the use of the component interfaces * for separate objects (player & NPC) and updating of these components as per the * implementations in GameObject class and the component classes. */ @Slf4j public final class App { /** * Program entry point. * * @param args args command line args. */ public static void main(String[] args) { final var player = GameObject.createPlayer(); final var npc = GameObject.createNpc(); LOGGER.info("Player Update:"); player.update(KeyEvent.KEY_LOCATION_LEFT); LOGGER.info("NPC Update:"); npc.demoUpdate(); } }
1,413
35.25641
94
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/GameObject.java
package com.iluwatar.component; import com.iluwatar.component.component.graphiccomponent.GraphicComponent; import com.iluwatar.component.component.graphiccomponent.ObjectGraphicComponent; import com.iluwatar.component.component.inputcomponent.DemoInputComponent; import com.iluwatar.component.component.inputcomponent.InputComponent; import com.iluwatar.component.component.inputcomponent.PlayerInputComponent; import com.iluwatar.component.component.physiccomponent.ObjectPhysicComponent; import com.iluwatar.component.component.physiccomponent.PhysicComponent; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * The GameObject class has three component class instances that allow * the creation of different game objects based on the game design requirements. */ @Getter @RequiredArgsConstructor public class GameObject { private final InputComponent inputComponent; private final PhysicComponent physicComponent; private final GraphicComponent graphicComponent; private final String name; private int velocity = 0; private int coordinate = 0; /** * Creates a player game object. * * @return player object */ public static GameObject createPlayer() { return new GameObject(new PlayerInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "player"); } /** * Creates a NPC game object. * * @return npc object */ public static GameObject createNpc() { return new GameObject( new DemoInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "npc"); } /** * Updates the three components of the NPC object used in the demo in App.java * note that this is simply a duplicate of update() without the key event for * demonstration purposes. * * <p>This method is usually used in games if the player becomes inactive. */ public void demoUpdate() { inputComponent.update(this, 0); physicComponent.update(this); graphicComponent.update(this); } /** * Updates the three components for objects based on key events. * * @param e key event from the player. */ public void update(int e) { inputComponent.update(this, e); physicComponent.update(this); graphicComponent.update(this); } /** * Update the velocity based on the acceleration of the GameObject. * * @param acceleration the acceleration of the GameObject */ public void updateVelocity(int acceleration) { this.velocity += acceleration; } /** * Set the c based on the current velocity. */ public void updateCoordinate() { this.coordinate += this.velocity; } }
2,695
27.378947
80
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/physiccomponent/PhysicComponent.java
package com.iluwatar.component.component.physiccomponent; import com.iluwatar.component.GameObject; /** * Generic PhysicComponent interface. */ public interface PhysicComponent { void update(GameObject gameObject); }
223
19.363636
57
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/physiccomponent/ObjectPhysicComponent.java
package com.iluwatar.component.component.physiccomponent; import com.iluwatar.component.GameObject; import lombok.extern.slf4j.Slf4j; /** * Take this component class to update the x coordinate for the Game Object instance. */ @Slf4j public class ObjectPhysicComponent implements PhysicComponent { /** * The method update the horizontal (X-axis) coordinate based on the velocity of gameObject. * * @param gameObject the gameObject instance */ @Override public void update(GameObject gameObject) { gameObject.updateCoordinate(); LOGGER.info(gameObject.getName() + "'s coordinate has been changed."); } }
635
26.652174
94
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/graphiccomponent/GraphicComponent.java
package com.iluwatar.component.component.graphiccomponent; import com.iluwatar.component.GameObject; /** * Generic GraphicComponent interface. */ public interface GraphicComponent { void update(GameObject gameObject); }
226
19.636364
58
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/graphiccomponent/ObjectGraphicComponent.java
package com.iluwatar.component.component.graphiccomponent; import com.iluwatar.component.GameObject; import lombok.extern.slf4j.Slf4j; /** * ObjectGraphicComponent class mimics the graphic component of the Game Object. */ @Slf4j public class ObjectGraphicComponent implements GraphicComponent { /** * The method updates the graphics based on the velocity of gameObject. * * @param gameObject the gameObject instance */ @Override public void update(GameObject gameObject) { LOGGER.info(gameObject.getName() + "'s current velocity: " + gameObject.getVelocity()); } }
594
26.045455
91
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/inputcomponent/PlayerInputComponent.java
package com.iluwatar.component.component.inputcomponent; import com.iluwatar.component.GameObject; import java.awt.event.KeyEvent; import lombok.extern.slf4j.Slf4j; /** * PlayerInputComponent is used to handle user key event inputs, * and thus it implements the InputComponent interface. */ @Slf4j public class PlayerInputComponent implements InputComponent { private static final int WALK_ACCELERATION = 1; /** * The update method to change the velocity based on the input key event. * * @param gameObject the gameObject instance * @param e key event instance */ @Override public void update(GameObject gameObject, int e) { switch (e) { case KeyEvent.KEY_LOCATION_LEFT -> { gameObject.updateVelocity(-WALK_ACCELERATION); LOGGER.info(gameObject.getName() + " has moved left."); } case KeyEvent.KEY_LOCATION_RIGHT -> { gameObject.updateVelocity(WALK_ACCELERATION); LOGGER.info(gameObject.getName() + " has moved right."); } default -> { LOGGER.info(gameObject.getName() + "'s velocity is unchanged due to the invalid input"); gameObject.updateVelocity(0); } // incorrect input } } }
1,214
30.153846
96
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/inputcomponent/InputComponent.java
package com.iluwatar.component.component.inputcomponent; import com.iluwatar.component.GameObject; /** * Generic InputComponent interface. */ public interface InputComponent { void update(GameObject gameObject, int e); }
227
19.727273
56
java
java-design-patterns
java-design-patterns-master/component/src/main/java/com/iluwatar/component/component/inputcomponent/DemoInputComponent.java
package com.iluwatar.component.component.inputcomponent; import com.iluwatar.component.GameObject; import lombok.extern.slf4j.Slf4j; /** * Take this component class to control player or the NPC for demo mode. * and implemented the InputComponent interface. * * <p>Essentially, the demo mode is utilised during a game if the user become inactive. * Please see: http://gameprogrammingpatterns.com/component.html */ @Slf4j public class DemoInputComponent implements InputComponent { private static final int WALK_ACCELERATION = 2; /** * Redundant method in the demo mode. * * @param gameObject the gameObject instance * @param e key event instance */ @Override public void update(GameObject gameObject, int e) { gameObject.updateVelocity(WALK_ACCELERATION); LOGGER.info(gameObject.getName() + " has moved right."); } }
867
28.931034
87
java
bitcoinj
bitcoinj-master/tools/src/main/java/org/bitcoinj/tools/BuildCheckpoints.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.tools; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.*; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import picocli.CommandLine; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.Future; import static java.util.concurrent.TimeUnit.SECONDS; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Downloads and verifies a full chain from your local peer, emitting checkpoints at each difficulty transition period * to a file which is then signed with your key. */ @CommandLine.Command(name = "build-checkpoints", usageHelpAutoWidth = true, sortOptions = false, description = "Create checkpoint files to use with CheckpointManager.") public class BuildCheckpoints implements Callable<Integer> { @CommandLine.Option(names = "--net", description = "Which network to connect to. Valid values: ${COMPLETION-CANDIDATES}. Default: ${DEFAULT-VALUE}") private BitcoinNetwork net = BitcoinNetwork.MAINNET; @CommandLine.Option(names = "--peer", description = "IP address/domain name for connection instead of localhost.") private String peer = null; @CommandLine.Option(names = "--days", description = "How many days to keep as a safety margin. Checkpointing will be done up to this many days ago.") private int days = 7; @CommandLine.Option(names = "--help", usageHelp = true, description = "Displays program options.") private boolean help; private static NetworkParameters params; public static void main(String[] args) throws Exception { BriefLogFormatter.initWithSilentBitcoinJ(); int exitCode = new CommandLine(new BuildCheckpoints()).execute(args); System.exit(exitCode); } @Override public Integer call() throws Exception { final String suffix; params = NetworkParameters.of(net); Context.propagate(new Context()); switch (net) { case MAINNET: suffix = ""; break; case TESTNET: suffix = "-testnet"; break; case SIGNET: suffix = "-signet"; break; case REGTEST: suffix = "-regtest"; break; default: throw new RuntimeException("Unreachable."); } // Configure bitcoinj to fetch only headers, not save them to disk, connect to a local fully synced/validated // node and to save block headers that are on interval boundaries, as long as they are <1 month old. final BlockStore store = new MemoryBlockStore(params.getGenesisBlock()); final BlockChain chain = new BlockChain(params, store); final PeerGroup peerGroup = new PeerGroup(net, chain); final InetAddress ipAddress; // DNS discovery can be used for some networks boolean networkHasDnsSeeds = params.getDnsSeeds() != null; if (peer != null) { // use peer provided in argument try { ipAddress = InetAddress.getByName(peer); startPeerGroup(peerGroup, ipAddress); } catch (UnknownHostException e) { System.err.println("Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage()); return 1; } } else if (networkHasDnsSeeds) { // use a peer group discovered with dns peerGroup.setUserAgent("PeerMonitor", "1.0"); peerGroup.setMaxConnections(20); peerGroup.addPeerDiscovery(new DnsDiscovery(params)); peerGroup.start(); // Connect to at least 4 peers because some may not support download Future<List<Peer>> future = peerGroup.waitForPeers(4); System.out.println("Connecting to " + params.getId() + ", timeout 20 seconds..."); // throw timeout exception if we can't get peers future.get(20, SECONDS); } else { // try localhost ipAddress = InetAddress.getLocalHost(); startPeerGroup(peerGroup, ipAddress); } // Sorted map of block height to StoredBlock object. final TreeMap<Integer, StoredBlock> checkpoints = new TreeMap<>(); Instant now = TimeUtils.currentTime(); peerGroup.setFastCatchupTime(now); Instant timeAgo = now.minus(days, ChronoUnit.DAYS); System.out.println("Checkpointing up to " + TimeUtils.dateTimeFormat(timeAgo)); chain.addNewBestBlockListener(Threading.SAME_THREAD, block -> { int height = block.getHeight(); if (height % params.getInterval() == 0 && timeAgo.isAfter(block.getHeader().time())) { System.out.println(String.format("Checkpointing block %s at height %d, time %s", block.getHeader().getHash(), block.getHeight(), TimeUtils.dateTimeFormat(block.getHeader().time()))); checkpoints.put(height, block); } }); peerGroup.downloadBlockChain(); checkState(checkpoints.size() > 0); final File plainFile = new File("checkpoints" + suffix); final File textFile = new File("checkpoints" + suffix + ".txt"); // Write checkpoint data out. writeBinaryCheckpoints(checkpoints, plainFile); writeTextualCheckpoints(checkpoints, textFile); peerGroup.stop(); store.close(); // Sanity check the created files. sanityCheck(plainFile, checkpoints.size()); sanityCheck(textFile, checkpoints.size()); return 0; } private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception { MessageDigest digest = Sha256Hash.newDigest(); try (FileOutputStream fileOutputStream = new FileOutputStream(file, false); DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest); DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream)) { digestOutputStream.on(false); dataOutputStream.writeBytes("CHECKPOINTS 1"); dataOutputStream.writeInt(0); // Number of signatures to read. Do this later. digestOutputStream.on(true); dataOutputStream.writeInt(checkpoints.size()); ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE); for (StoredBlock block : checkpoints.values()) { block.serializeCompact(buffer); dataOutputStream.write(buffer.array()); ((Buffer) buffer).position(0); } Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest()); System.out.println("Hash of checkpoints data is " + checkpointsHash); System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'."); } } private static void writeTextualCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws IOException { try (PrintWriter writer = new PrintWriter( new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.US_ASCII))) { writer.println("TXT CHECKPOINTS 1"); writer.println("0"); // Number of signatures to read. Do this later. writer.println(checkpoints.size()); ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE); for (StoredBlock block : checkpoints.values()) { block.serializeCompact(buffer); writer.println(CheckpointManager.BASE64.encode(buffer.array())); ((Buffer) buffer).position(0); } System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'."); } } private static void sanityCheck(File file, int expectedSize) throws IOException { FileInputStream fis = new FileInputStream(file); CheckpointManager manager; try { manager = new CheckpointManager(params, fis); } finally { fis.close(); } checkState(manager.numCheckpoints() == expectedSize); if (params.network() == BitcoinNetwork.MAINNET) { StoredBlock test = manager.getCheckpointBefore(Instant.ofEpochSecond(1390500000)); // Thu Jan 23 19:00:00 CET 2014 checkState(test.getHeight() == 280224); checkState(test.getHeader().getHashAsString() .equals("00000000000000000b5d59a15f831e1c45cb688a4db6b0a60054d49a9997fa34")); } else if (params.network() == BitcoinNetwork.TESTNET) { StoredBlock test = manager.getCheckpointBefore(Instant.ofEpochSecond(1390500000)); // Thu Jan 23 19:00:00 CET 2014 checkState(test.getHeight() == 167328); checkState(test.getHeader().getHashAsString() .equals("0000000000035ae7d5025c2538067fe7adb1cf5d5d9c31b024137d9090ed13a9")); } else if (params.network() == BitcoinNetwork.SIGNET) { StoredBlock test = manager.getCheckpointBefore(Instant.ofEpochSecond(1642000000)); // 2022-01-12 checkState(test.getHeight() == 72576); checkState(test.getHeader().getHashAsString() .equals("0000008f763bdf23bd159a21ccf211098707671d2ca9aa72d0f586c24505c5e7")); } } private static void startPeerGroup(PeerGroup peerGroup, InetAddress ipAddress) { final PeerAddress peerAddress = PeerAddress.simple(ipAddress, params.getPort()); System.out.println("Connecting to " + peerAddress + "..."); peerGroup.addAddress(peerAddress); peerGroup.start(); } }
11,225
43.371542
168
java
bitcoinj
bitcoinj-master/tools/src/main/java/org/bitcoinj/tools/PaymentProtocolTool.java
/* * Copyright 2014 The bitcoinj team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.tools; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.TrustStoreLoader; import org.bitcoinj.protocols.payments.PaymentProtocol; import org.bitcoinj.protocols.payments.PaymentProtocolException; import org.bitcoinj.protocols.payments.PaymentSession; import org.bitcoinj.uri.BitcoinURI; import org.bitcoinj.uri.BitcoinURIParseException; import org.bitcoin.protocols.payments.Protos; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyStoreException; import java.security.cert.X509Certificate; import java.time.Instant; import java.util.Date; import java.util.concurrent.ExecutionException; import static java.lang.String.format; /** Takes a URL or bitcoin URI and prints information about the payment request. */ public class PaymentProtocolTool { public static void main(String[] args) { if (args.length < 1) { System.err.println("Provide a bitcoin URI or URL as the argument."); return; } dump(args[0]); } private static void dump(String arg) { try { URI uri = new URI(arg); PaymentSession session; if (arg.startsWith("/")) { FileInputStream stream = new FileInputStream(arg); Protos.PaymentRequest request = Protos.PaymentRequest.parseFrom(stream); stream.close(); session = new PaymentSession(request); } else if ("http".equals(uri.getScheme())) { session = PaymentSession.createFromUrl(arg).get(); } else if ("bitcoin".equals(uri.getScheme())) { BitcoinURI bcuri = BitcoinURI.of(arg); final String paymentRequestUrl = bcuri.getPaymentRequestUrl(); if (paymentRequestUrl == null) { System.err.println("No r= param in bitcoin URI"); return; } session = PaymentSession.createFromBitcoinUri(bcuri).get(); } else { System.err.println("Unknown URI scheme: " + uri.getScheme()); return; } final int version = session.getPaymentRequest().getPaymentDetailsVersion(); StringBuilder output = new StringBuilder( format("Bitcoin payment request, version %d%nDate: %s%n", version, session.time())); PaymentProtocol.PkiVerificationData pki = PaymentProtocol.verifyPaymentRequestPki( session.getPaymentRequest(), new TrustStoreLoader.DefaultTrustStoreLoader().getKeyStore()); if (pki != null) { output.append(format("Signed by: %s%nIdentity verified by: %s%n", pki.displayName, pki.rootAuthorityName)); } if (session.getPaymentDetails().hasExpires()) { output.append(format("Expires: %s%n", TimeUtils.dateTimeFormat(Instant.ofEpochSecond(session.getPaymentDetails().getExpires())))); } if (session.getMemo() != null) { output.append(format("Memo: %s%n", session.getMemo())); } output.append(format("%n%n%s%n%s", session.getPaymentRequest(), session.getPaymentDetails())); System.out.println(output); } catch (URISyntaxException | BitcoinURIParseException e) { System.err.println("Could not parse URI: " + e.getMessage()); } catch (PaymentProtocolException.PkiVerificationException e) { System.err.println(e.getMessage()); if (e.certificates != null) { for (X509Certificate certificate : e.certificates) { System.err.println(" " + certificate); } } } catch (PaymentProtocolException e) { System.err.println("Could not handle payment request: " + e.getMessage()); } catch (InterruptedException e) { System.err.println("Interrupted whilst processing/downloading."); } catch (ExecutionException e) { System.err.println("Failed whilst retrieving payment URL: " + e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } catch (IOException | KeyStoreException e) { e.printStackTrace(); } } }
5,052
43.716814
146
java
bitcoinj
bitcoinj-master/tools/src/main/java/org/bitcoinj/tools/TestFeeLevel.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.tools; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.core.*; import org.bitcoinj.core.listeners.PeerConnectedEventListener; import org.bitcoinj.core.listeners.PeerDisconnectedEventListener; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.KeyChainGroupStructure; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import java.io.File; import java.util.concurrent.ExecutionException; /** * A program that sends a transaction with the specified fee and measures how long it takes to confirm. */ public class TestFeeLevel { private static final int NUM_OUTPUTS = 2; private static WalletAppKit kit; public static void main(String[] args) throws Exception { BriefLogFormatter.initWithSilentBitcoinJ(); if (args.length == 0) { System.err.println("Specify the fee rate to test in satoshis/kB as the first argument."); return; } Coin feeRateToTest = Coin.valueOf(Long.parseLong(args[0])); System.out.println("Fee rate to test is " + feeRateToTest.toFriendlyString() + "/kB"); kit = new WalletAppKit(BitcoinNetwork.MAINNET, ScriptType.P2WPKH, KeyChainGroupStructure.BIP32, new File("."), "testfeelevel"); kit.startAsync(); kit.awaitRunning(); try { go(feeRateToTest, NUM_OUTPUTS); } finally { kit.stopAsync(); kit.awaitTerminated(); } } private static void go(Coin feeRateToTest, int numOutputs) throws InterruptedException, ExecutionException, InsufficientMoneyException { System.out.println("Wallet has " + kit.wallet().getBalance().toFriendlyString() + "; current receive address is " + kit.wallet().currentReceiveAddress()); kit.peerGroup().setMaxConnections(25); if (kit.wallet().getBalance().compareTo(feeRateToTest) < 0) { System.out.println("Send some coins to receive address and wait for it to confirm ..."); kit.wallet().getBalanceFuture(feeRateToTest, Wallet.BalanceType.AVAILABLE).get(); } int heightAtStart = kit.chain().getBestChainHeight(); System.out.println("Height at start is " + heightAtStart); Coin value = kit.wallet().getBalance().divide(2); // Keep a chunk for the fee. Coin outputValue = value.divide(numOutputs); Transaction transaction = new Transaction(); for (int i = 0; i < numOutputs - 1; i++) { transaction.addOutput(outputValue, kit.wallet().freshReceiveAddress()); value = value.subtract(outputValue); } transaction.addOutput(value, kit.wallet().freshReceiveAddress()); SendRequest request = SendRequest.forTx(transaction); request.feePerKb = feeRateToTest; request.ensureMinRequiredFee = false; kit.wallet().completeTx(request); System.out.println("Size in bytes is " + request.tx.serialize().length); System.out.println("TX is " + request.tx); System.out.println("Waiting for " + kit.peerGroup().getMaxConnections() + " connected peers"); kit.peerGroup().addDisconnectedEventListener((peer, peerCount) -> System.out.println(peerCount + " peers connected")); kit.peerGroup().addConnectedEventListener((peer, peerCount) -> System.out.println(peerCount + " peers connected")); kit.peerGroup().broadcastTransaction(request.tx).awaitRelayed().get(); System.out.println("Send complete, waiting for confirmation"); request.tx.getConfidence().getDepthFuture(1).get(); int heightNow = kit.chain().getBestChainHeight(); System.out.println("Height after confirmation is " + heightNow); System.out.println("Result: took " + (heightNow - heightAtStart) + " blocks to confirm at this fee level"); } }
4,619
43
140
java
bitcoinj
bitcoinj-master/tools/src/main/java/org/bitcoinj/tools/BlockImporter.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.tools; import org.bitcoinj.core.*; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.store.*; import org.bitcoinj.utils.BlockFileLoader; import java.io.File; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** Very thin wrapper around {@link BlockFileLoader} */ public class BlockImporter { public static void main(String[] args) throws BlockStoreException, VerificationException, PrunedException { System.out.println("USAGE: BlockImporter (prod|test) (Disk|MemFull|Mem|SPV) [blockStore]"); System.out.println(" blockStore is required unless type is Mem or MemFull"); System.out.println(" Does full verification if the store supports it"); checkArgument(args.length == 2 || args.length == 3); NetworkParameters params; if (args[0].equals("test")) params = TestNet3Params.get(); else params = MainNetParams.get(); BlockStore store; switch (args[1]) { case "MemFull": checkArgument(args.length == 2); store = new MemoryFullPrunedBlockStore(params, 100); break; case "Mem": checkArgument(args.length == 2); store = new MemoryBlockStore(params.getGenesisBlock()); break; case "SPV": checkArgument(args.length == 3); store = new SPVBlockStore(params, new File(args[2])); break; default: System.err.println("Unknown store " + args[1]); return; } AbstractBlockChain chain = null; if (store instanceof FullPrunedBlockStore) chain = new FullPrunedBlockChain(params, (FullPrunedBlockStore) store); else chain = new BlockChain(params, store); BlockFileLoader loader = new BlockFileLoader(params.network(), BlockFileLoader.getReferenceClientBlockFileList()); for (Block block : loader) chain.add(block); } }
2,773
36.486486
122
java
bitcoinj
bitcoinj-master/tools/src/main/java/org/bitcoinj/tools/WatchMempool.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.tools; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.listeners.*; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.core.Transaction; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DefaultRiskAnalysis; import org.bitcoinj.wallet.RiskAnalysis.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WatchMempool { private static final Logger log = LoggerFactory.getLogger(WatchMempool.class); private static final Network NETWORK = BitcoinNetwork.MAINNET; private static final List<Transaction> NO_DEPS = Collections.emptyList(); private static final Map<String, Integer> counters = new HashMap<>(); private static final String TOTAL_KEY = "TOTAL"; private static final Instant START = TimeUtils.currentTime(); private static final Duration STATISTICS_FREQUENCY = Duration.ofSeconds(5); public static void main(String[] args) throws InterruptedException { BriefLogFormatter.init(); PeerGroup peerGroup = new PeerGroup(NETWORK); peerGroup.setMaxConnections(32); peerGroup.addPeerDiscovery(new DnsDiscovery(NetworkParameters.of(NETWORK))); peerGroup.addOnTransactionBroadcastListener((peer, tx) -> { Result result = DefaultRiskAnalysis.FACTORY.create(null, tx, NO_DEPS).analyze(); incrementCounter(TOTAL_KEY); log.info("tx {} result {}", tx.getTxId(), result); incrementCounter(result.name()); if (result == Result.NON_STANDARD) incrementCounter(Result.NON_STANDARD + "-" + DefaultRiskAnalysis.isStandard(tx)); }); peerGroup.start(); while (true) { Thread.sleep(STATISTICS_FREQUENCY.toMillis()); printCounters(); } } private static synchronized void incrementCounter(String name) { Integer count = counters.get(name); if (count == null) count = 0; count++; counters.put(name, count); } private static synchronized void printCounters() { Duration elapsed = TimeUtils.elapsedTime(START); System.out.printf("Runtime: %d:%02d minutes\n", elapsed.toMinutes(), elapsed.toSecondsPart()); Integer total = counters.get(TOTAL_KEY); if (total == null) return; for (Map.Entry<String, Integer> counter : counters.entrySet()) { System.out.printf(" %-40s%6d (%d%% of total)\n", counter.getKey(), counter.getValue(), (int) counter.getValue() * 100 / total); } } }
3,596
38.097826
102
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/HDPathTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Michael Sean Gilligan */ public class HDPathTest { @Test public void testPrimaryConstructor() { HDPath path = new HDPath(true, Collections.emptyList()); assertTrue("Has private key returns false incorrectly", path.hasPrivateKey); assertEquals("Path not empty", path.size(), 0); } @Test public void testExtendVarargs() { HDPath basePath = new HDPath(true, Collections.emptyList()); assertTrue(basePath.hasPrivateKey()); assertEquals("m", basePath.toString()); // Make sure we can do a depth of 5 as per BIP44, etc. // m / 44' / coinType' / accountIndex' / change / addressIndex HDPath path1 = basePath.extend(ChildNumber.ZERO_HARDENED); HDPath path2 = basePath.extend(ChildNumber.ZERO_HARDENED, ChildNumber.ONE_HARDENED); HDPath path3 = basePath.extend(ChildNumber.ZERO_HARDENED, ChildNumber.ONE_HARDENED, ChildNumber.ZERO_HARDENED); HDPath path4 = basePath.extend(ChildNumber.ZERO_HARDENED, ChildNumber.ONE_HARDENED, ChildNumber.ZERO_HARDENED, ChildNumber.ONE); HDPath path5 = basePath.extend(ChildNumber.ZERO_HARDENED, ChildNumber.ONE_HARDENED, ChildNumber.ZERO_HARDENED, ChildNumber.ONE, ChildNumber.ZERO); assertEquals("m/0H", path1.toString()); assertEquals("m/0H/1H", path2.toString()); assertEquals("m/0H/1H/0H", path3.toString()); assertEquals("m/0H/1H/0H/1", path4.toString()); assertEquals("m/0H/1H/0H/1/0", path5.toString()); } @Test public void testParent() { HDPath path1 = HDPath.parsePath("m/0H/1H"); assertEquals(HDPath.parsePath("m/0H"), path1.parent()); HDPath path2 = HDPath.parsePath("m/0H"); assertEquals(HDPath.parsePath(""), path2.parent()); HDPath path3 = HDPath.parsePath(""); assertEquals(HDPath.parsePath(""), path3.parent()); } @Test public void testAncestors() { HDPath path = HDPath.parsePath("m/0H/1H/0H/1/0"); List<HDPath> ancestors = path.ancestors(); assertEquals(4, ancestors.size()); assertEquals(HDPath.parsePath("m/0H"), ancestors.get(0)); assertEquals(HDPath.parsePath("m/0H/1H"), ancestors.get(1)); assertEquals(HDPath.parsePath("m/0H/1H/0H"), ancestors.get(2)); assertEquals(HDPath.parsePath("m/0H/1H/0H/1"), ancestors.get(3)); List<HDPath> ancestorsWithSelf = path.ancestors(true); assertEquals(5, ancestorsWithSelf.size()); assertEquals(HDPath.parsePath("m/0H"), ancestorsWithSelf.get(0)); assertEquals(HDPath.parsePath("m/0H/1H"), ancestorsWithSelf.get(1)); assertEquals(HDPath.parsePath("m/0H/1H/0H"), ancestorsWithSelf.get(2)); assertEquals(HDPath.parsePath("m/0H/1H/0H/1"), ancestorsWithSelf.get(3)); assertEquals(HDPath.parsePath("m/0H/1H/0H/1/0"), ancestorsWithSelf.get(4)); HDPath rootPath = HDPath.parsePath("m/0H"); List<HDPath> empty = rootPath.ancestors(); assertEquals(0, empty.size()); List<HDPath> self = rootPath.ancestors(true); assertEquals(1, self.size()); assertEquals(rootPath, self.get(0)); HDPath emptyPath = HDPath.m(); List<HDPath> empty2 = emptyPath.ancestors(); assertEquals(0, empty2.size()); List<HDPath> empty3 = emptyPath.ancestors(true); assertEquals(0, empty3.size()); } @Test public void testFormatPath() { Object[] tv = { "M/44H/0H/0H/1/1", HDPath.M(new ChildNumber(44, true), new ChildNumber(0, true), new ChildNumber(0, true), new ChildNumber(1, false), new ChildNumber(1, false)), "M/7H/3/3/1H", HDPath.M(new ChildNumber(7, true), new ChildNumber(3, false), new ChildNumber(3, false), new ChildNumber(1, true)), "M/1H/2H/3H", HDPath.M(new ChildNumber(1, true), new ChildNumber(2, true), new ChildNumber(3, true)), "M/1/2/3", HDPath.M(new ChildNumber(1, false), new ChildNumber(2, false), new ChildNumber(3, false)) }; for (int i = 0; i < tv.length; i += 2) { String expectedStrPath = (String) tv[i]; HDPath path = (HDPath) tv[i + 1]; String generatedStrPath = path.toString(); assertEquals(generatedStrPath, expectedStrPath); } } @Test public void testParsePath() { Object[] tv = { "M / 44H / 0H / 0H / 1 / 1", HDPath.M(new ChildNumber(44, true), new ChildNumber(0, true), new ChildNumber(0, true), new ChildNumber(1, false), new ChildNumber(1, false)), false, "M/7H/3/3/1H/", HDPath.M(new ChildNumber(7, true), new ChildNumber(3, false), new ChildNumber(3, false), new ChildNumber(1, true)), false, "m/7H/3/3/1H/", HDPath.m(new ChildNumber(7, true), new ChildNumber(3, false), new ChildNumber(3, false), new ChildNumber(1, true)), true, "1 H / 2 H / 3 H /", Arrays.asList(new ChildNumber(1, true), new ChildNumber(2, true), new ChildNumber(3, true)), false, "1 / 2 / 3 /", Arrays.asList(new ChildNumber(1, false), new ChildNumber(2, false), new ChildNumber(3, false)), false }; for (int i = 0; i < tv.length; i += 3) { String strPath = (String) tv[i]; List<ChildNumber> expectedPath = (List<ChildNumber>) tv[i + 1]; boolean expectedHasPrivateKey = (Boolean) tv[i + 2]; HDPath path = HDPath.parsePath(strPath); assertEquals(path, expectedPath); assertEquals(path.hasPrivateKey, expectedHasPrivateKey); } } }
6,894
35.871658
154
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java
/* * Copyright 2013 Matija Mazi. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.Network; import org.bitcoinj.base.Sha256Hash; import static org.bitcoinj.base.BitcoinNetwork.MAINNET; import static org.bitcoinj.base.BitcoinNetwork.TESTNET; import org.junit.Test; import org.bitcoinj.base.internal.ByteUtils; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * This test is adapted from Armory's BIP 32 tests. */ public class ChildKeyDerivationTest { private static final int SCRYPT_ITERATIONS = 256; private static final int HDW_CHAIN_EXTERNAL = 0; private static final int HDW_CHAIN_INTERNAL = 1; @Test public void testChildKeyDerivation() { String[] ckdTestVectors = { // test case 1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "04" + "6a04ab98d9e4774ad806e302dddeb63b" + "ea16b5cb5f223ee77478e861bb583eb3" + "36b6fbcb60b5b3d4f1551ac45e5ffc49" + "36466e7d98f6c7c0ec736539f74691a6", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", // test case 2: "be05d9ded0a73f81b814c93792f753b35c575fe446760005d44e0be13ba8935a", "02" + "b530da16bbff1428c33020e87fc9e699" + "cc9c753a63b8678ce647b7457397acef", "7012bc411228495f25d666d55fdce3f10a93908b5f9b9b7baa6e7573603a7bda" }; assertEquals(0, ckdTestVectors.length % 3); for(int i = 0; i < ckdTestVectors.length / 3; i++) { byte[] priv = ByteUtils.parseHex(ckdTestVectors[3 * i]); byte[] pub = ByteUtils.parseHex(ckdTestVectors[3 * i + 1]); byte[] chain = ByteUtils.parseHex(ckdTestVectors[3 * i + 2]); // chain code ////////////////////////////////////////////////////////////////////////// // Start with an extended PRIVATE key DeterministicKey ekprv = HDKeyDerivation.createMasterPrivKeyFromBytes(priv, chain); assertEquals("m", ekprv.getPath().toString()); // Create two accounts DeterministicKey ekprv_0 = HDKeyDerivation.deriveChildKey(ekprv, 0); assertEquals("m/0", ekprv_0.getPath().toString()); DeterministicKey ekprv_1 = HDKeyDerivation.deriveChildKey(ekprv, 1); assertEquals("m/1", ekprv_1.getPath().toString()); // Create internal and external chain on Account 0 DeterministicKey ekprv_0_EX = HDKeyDerivation.deriveChildKey(ekprv_0, HDW_CHAIN_EXTERNAL); assertEquals("m/0/0", ekprv_0_EX.getPath().toString()); DeterministicKey ekprv_0_IN = HDKeyDerivation.deriveChildKey(ekprv_0, HDW_CHAIN_INTERNAL); assertEquals("m/0/1", ekprv_0_IN.getPath().toString()); // Create three addresses on external chain DeterministicKey ekprv_0_EX_0 = HDKeyDerivation.deriveChildKey(ekprv_0_EX, 0); assertEquals("m/0/0/0", ekprv_0_EX_0.getPath().toString()); DeterministicKey ekprv_0_EX_1 = HDKeyDerivation.deriveChildKey(ekprv_0_EX, 1); assertEquals("m/0/0/1", ekprv_0_EX_1.getPath().toString()); DeterministicKey ekprv_0_EX_2 = HDKeyDerivation.deriveChildKey(ekprv_0_EX, 2); assertEquals("m/0/0/2", ekprv_0_EX_2.getPath().toString()); // Create three addresses on internal chain DeterministicKey ekprv_0_IN_0 = HDKeyDerivation.deriveChildKey(ekprv_0_IN, 0); assertEquals("m/0/1/0", ekprv_0_IN_0.getPath().toString()); DeterministicKey ekprv_0_IN_1 = HDKeyDerivation.deriveChildKey(ekprv_0_IN, 1); assertEquals("m/0/1/1", ekprv_0_IN_1.getPath().toString()); DeterministicKey ekprv_0_IN_2 = HDKeyDerivation.deriveChildKey(ekprv_0_IN, 2); assertEquals("m/0/1/2", ekprv_0_IN_2.getPath().toString()); // Now add a few more addresses with very large indices DeterministicKey ekprv_1_IN = HDKeyDerivation.deriveChildKey(ekprv_1, HDW_CHAIN_INTERNAL); assertEquals("m/1/1", ekprv_1_IN.getPath().toString()); DeterministicKey ekprv_1_IN_4095 = HDKeyDerivation.deriveChildKey(ekprv_1_IN, 4095); assertEquals("m/1/1/4095", ekprv_1_IN_4095.getPath().toString()); ////////////////////////////////////////////////////////////////////////// // Repeat the above with PUBLIC key DeterministicKey ekpub = HDKeyDerivation.createMasterPubKeyFromBytes(HDUtils.toCompressed(pub), chain); assertEquals("M", ekpub.getPath().toString()); // Create two accounts DeterministicKey ekpub_0 = HDKeyDerivation.deriveChildKey(ekpub, 0); assertEquals("M/0", ekpub_0.getPath().toString()); DeterministicKey ekpub_1 = HDKeyDerivation.deriveChildKey(ekpub, 1); assertEquals("M/1", ekpub_1.getPath().toString()); // Create internal and external chain on Account 0 DeterministicKey ekpub_0_EX = HDKeyDerivation.deriveChildKey(ekpub_0, HDW_CHAIN_EXTERNAL); assertEquals("M/0/0", ekpub_0_EX.getPath().toString()); DeterministicKey ekpub_0_IN = HDKeyDerivation.deriveChildKey(ekpub_0, HDW_CHAIN_INTERNAL); assertEquals("M/0/1", ekpub_0_IN.getPath().toString()); // Create three addresses on external chain DeterministicKey ekpub_0_EX_0 = HDKeyDerivation.deriveChildKey(ekpub_0_EX, 0); assertEquals("M/0/0/0", ekpub_0_EX_0.getPath().toString()); DeterministicKey ekpub_0_EX_1 = HDKeyDerivation.deriveChildKey(ekpub_0_EX, 1); assertEquals("M/0/0/1", ekpub_0_EX_1.getPath().toString()); DeterministicKey ekpub_0_EX_2 = HDKeyDerivation.deriveChildKey(ekpub_0_EX, 2); assertEquals("M/0/0/2", ekpub_0_EX_2.getPath().toString()); // Create three addresses on internal chain DeterministicKey ekpub_0_IN_0 = HDKeyDerivation.deriveChildKey(ekpub_0_IN, 0); assertEquals("M/0/1/0", ekpub_0_IN_0.getPath().toString()); DeterministicKey ekpub_0_IN_1 = HDKeyDerivation.deriveChildKey(ekpub_0_IN, 1); assertEquals("M/0/1/1", ekpub_0_IN_1.getPath().toString()); DeterministicKey ekpub_0_IN_2 = HDKeyDerivation.deriveChildKey(ekpub_0_IN, 2); assertEquals("M/0/1/2", ekpub_0_IN_2.getPath().toString()); // Now add a few more addresses with very large indices DeterministicKey ekpub_1_IN = HDKeyDerivation.deriveChildKey(ekpub_1, HDW_CHAIN_INTERNAL); assertEquals("M/1/1", ekpub_1_IN.getPath().toString()); DeterministicKey ekpub_1_IN_4095 = HDKeyDerivation.deriveChildKey(ekpub_1_IN, 4095); assertEquals("M/1/1/4095", ekpub_1_IN_4095.getPath().toString()); assertEquals(hexEncodePub(ekprv.dropPrivateBytes().dropParent()), hexEncodePub(ekpub)); assertEquals(hexEncodePub(ekprv_0.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0)); assertEquals(hexEncodePub(ekprv_1.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_1)); assertEquals(hexEncodePub(ekprv_0_IN.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_IN)); assertEquals(hexEncodePub(ekprv_0_IN_0.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_IN_0)); assertEquals(hexEncodePub(ekprv_0_IN_1.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_IN_1)); assertEquals(hexEncodePub(ekprv_0_IN_2.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_IN_2)); assertEquals(hexEncodePub(ekprv_0_EX_0.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_EX_0)); assertEquals(hexEncodePub(ekprv_0_EX_1.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_EX_1)); assertEquals(hexEncodePub(ekprv_0_EX_2.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_0_EX_2)); assertEquals(hexEncodePub(ekprv_1_IN.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_1_IN)); assertEquals(hexEncodePub(ekprv_1_IN_4095.dropPrivateBytes().dropParent()), hexEncodePub(ekpub_1_IN_4095)); } } @Test public void inverseEqualsNormal() { DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("Wired / Aug 13th 2014 / Snowden: I Left the NSA Clues, But They Couldn't Find Them".getBytes()); HDKeyDerivation.RawKeyBytes key2 = HDKeyDerivation.deriveChildKeyBytesFromPublic(key1.dropPrivateBytes().dropParent(), ChildNumber.ZERO, HDKeyDerivation.PublicDeriveMode.NORMAL); HDKeyDerivation.RawKeyBytes key3 = HDKeyDerivation.deriveChildKeyBytesFromPublic(key1.dropPrivateBytes().dropParent(), ChildNumber.ZERO, HDKeyDerivation.PublicDeriveMode.WITH_INVERSION); assertArrayEquals(key2.keyBytes, key3.keyBytes); assertArrayEquals(key2.chainCode, key3.chainCode); } @Test public void encryptedDerivation() { // Check that encrypting a parent key in the hierarchy and then deriving from it yields a DeterministicKey // with no private key component, and that the private key bytes are derived on demand. KeyCrypter scrypter = new KeyCrypterScrypt(SCRYPT_ITERATIONS); AesKey aesKey = scrypter.deriveKey("we never went to the moon"); DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("it was all a hoax".getBytes()); DeterministicKey encryptedKey1 = key1.encrypt(scrypter, aesKey, null); DeterministicKey decryptedKey1 = encryptedKey1.decrypt(aesKey); assertEquals(key1, decryptedKey1); DeterministicKey key2 = HDKeyDerivation.deriveChildKey(key1, ChildNumber.ZERO); DeterministicKey derivedKey2 = HDKeyDerivation.deriveChildKey(encryptedKey1, ChildNumber.ZERO); assertTrue(derivedKey2.isEncrypted()); // parent is encrypted. DeterministicKey decryptedKey2 = derivedKey2.decrypt(aesKey); assertFalse(decryptedKey2.isEncrypted()); assertEquals(key2, decryptedKey2); Sha256Hash hash = Sha256Hash.of("the mainstream media won't cover it. why is that?".getBytes()); try { derivedKey2.sign(hash); fail(); } catch (ECKey.KeyIsEncryptedException e) { // Ignored. } ECKey.ECDSASignature signature = derivedKey2.sign(hash, aesKey); assertTrue(derivedKey2.verify(hash, signature)); } @Test public void pubOnlyDerivation() { DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes()); assertFalse(key1.isPubKeyOnly()); DeterministicKey key2 = HDKeyDerivation.deriveChildKey(key1, ChildNumber.ZERO_HARDENED); assertFalse(key2.isPubKeyOnly()); DeterministicKey key3 = HDKeyDerivation.deriveChildKey(key2, ChildNumber.ZERO); assertFalse(key3.isPubKeyOnly()); key2 = key2.dropPrivateBytes(); assertFalse(key2.isPubKeyOnly()); // still got private key bytes from the parents! // pubkey2 got its cached private key bytes (if any) dropped, and now it'll lose its parent too, so now it // becomes a true pubkey-only object. DeterministicKey pubkey2 = key2.dropParent(); DeterministicKey pubkey3 = HDKeyDerivation.deriveChildKey(pubkey2, ChildNumber.ZERO); assertTrue(pubkey3.isPubKeyOnly()); assertEquals(key3.getPubKeyPoint(), pubkey3.getPubKeyPoint()); } @Test public void testSerializationMainAndTestNetworks() { DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes()); String pub58 = key1.serializePubB58(MAINNET); String priv58 = key1.serializePrivB58(MAINNET); assertEquals("xpub661MyMwAqRbcF7mq7Aejj5xZNzFfgi3ABamE9FedDHVmViSzSxYTgAQGcATDo2J821q7Y9EAagjg5EP3L7uBZk11PxZU3hikL59dexfLkz3", pub58); assertEquals("xprv9s21ZrQH143K2dhN197jMx1ppxRBHFKJpMqdLsF1ewxncv7quRED8N5nksxphju3W7naj1arF56L5PUEWfuSk8h73Sb2uh7bSwyXNrjzhAZ", priv58); pub58 = key1.serializePubB58(TESTNET); priv58 = key1.serializePrivB58(TESTNET); assertEquals("tpubD6NzVbkrYhZ4WuxgZMdpw1Hvi7MKg6YDjDMXVohmZCFfF17hXBPYpc56rCY1KXFMovN29ik37nZimQseiykRTBTJTZJmjENyv2k3R12BJ1M", pub58); assertEquals("tprv8ZgxMBicQKsPdSvtfhyEXbdp95qPWmMK9ukkDHfU8vTGQWrvtnZxe7TEg48Ui7HMsZKMj7CcQRg8YF1ydtFPZBxha5oLa3qeN3iwpYhHPVZ", priv58); } @Test public void serializeToTextAndBytes() { DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes()); DeterministicKey key2 = HDKeyDerivation.deriveChildKey(key1, ChildNumber.ZERO_HARDENED); // Creation time can't survive the xpub serialization format unfortunately. key1.clearCreationTime(); Network network = MAINNET; { final String pub58 = key1.serializePubB58(network); final String priv58 = key1.serializePrivB58(network); final byte[] pub = key1.serialize(network, true); final byte[] priv = key1.serialize(network, false); assertEquals("xpub661MyMwAqRbcF7mq7Aejj5xZNzFfgi3ABamE9FedDHVmViSzSxYTgAQGcATDo2J821q7Y9EAagjg5EP3L7uBZk11PxZU3hikL59dexfLkz3", pub58); assertEquals("xprv9s21ZrQH143K2dhN197jMx1ppxRBHFKJpMqdLsF1ewxncv7quRED8N5nksxphju3W7naj1arF56L5PUEWfuSk8h73Sb2uh7bSwyXNrjzhAZ", priv58); assertArrayEquals(new byte[]{4, -120, -78, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, -68, 93, -104, -97, 31, -105, -18, 109, 112, 104, 45, -77, -77, 18, 85, -29, -120, 86, -113, 26, 48, -18, -79, -110, -6, -27, 87, 86, 24, 124, 99, 3, 96, -33, -14, 67, -19, -47, 16, 76, -49, -11, -30, -123, 7, 56, 101, 91, 74, 125, -127, 61, 42, -103, 90, -93, 66, -36, 2, -126, -107, 30, 24, -111}, pub); assertArrayEquals(new byte[]{4, -120, -83, -28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, -68, 93, -104, -97, 31, -105, -18, 109, 112, 104, 45, -77, -77, 18, 85, -29, -120, 86, -113, 26, 48, -18, -79, -110, -6, -27, 87, 86, 24, 124, 99, 0, -96, -75, 47, 90, -49, 92, -74, 92, -128, -125, 23, 38, -10, 97, -66, -19, 50, -112, 30, -111, -57, -124, 118, -86, 126, -35, -4, -51, 19, 109, 67, 116}, priv); assertEquals(DeterministicKey.deserializeB58(null, priv58, network), key1); assertEquals(DeterministicKey.deserializeB58(priv58, network), key1); assertEquals(DeterministicKey.deserializeB58(null, pub58, network).getPubKeyPoint(), key1.getPubKeyPoint()); assertEquals(DeterministicKey.deserializeB58(pub58, network).getPubKeyPoint(), key1.getPubKeyPoint()); assertEquals(DeterministicKey.deserialize(network, priv, null), key1); assertEquals(DeterministicKey.deserialize(network, priv), key1); assertEquals(DeterministicKey.deserialize(network, pub, null).getPubKeyPoint(), key1.getPubKeyPoint()); assertEquals(DeterministicKey.deserialize(network, pub).getPubKeyPoint(), key1.getPubKeyPoint()); } { final String pub58 = key2.serializePubB58(network); final String priv58 = key2.serializePrivB58(network); final byte[] pub = key2.serialize(network, true); final byte[] priv = key2.serialize(network, false); assertEquals(DeterministicKey.deserializeB58(key1, priv58, network), key2); assertEquals(DeterministicKey.deserializeB58(key1, pub58, network).getPubKeyPoint(), key2.getPubKeyPoint()); assertEquals(DeterministicKey.deserialize(network, priv, key1), key2); assertEquals(DeterministicKey.deserialize(network, pub, key1).getPubKeyPoint(), key2.getPubKeyPoint()); } } @Test public void parentlessDeserialization() { DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes()); DeterministicKey key2 = HDKeyDerivation.deriveChildKey(key1, ChildNumber.ZERO_HARDENED); DeterministicKey key3 = HDKeyDerivation.deriveChildKey(key2, ChildNumber.ZERO_HARDENED); DeterministicKey key4 = HDKeyDerivation.deriveChildKey(key3, ChildNumber.ZERO_HARDENED); assertEquals(key4.getPath().size(), 3); assertEquals(DeterministicKey.deserialize(TESTNET, key4.serialize(TESTNET, false), key3).getPath().size(), 3); assertEquals(DeterministicKey.deserialize(TESTNET, key4.serialize(TESTNET, false), null).getPath().size(), 1); assertEquals(DeterministicKey.deserialize(TESTNET, key4.serialize(TESTNET, false)).getPath().size(), 1); } /** Reserializing a deserialized key should yield the original input */ @Test public void reserialization() { // This is the public encoding of the key with path m/0H/1/2H from BIP32 published test vector 1: // https://en.bitcoin.it/wiki/BIP_0032_TestVectors String encoded = "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5"; DeterministicKey key = DeterministicKey.deserializeB58(encoded, MAINNET); assertEquals("Reserialized parentless private HD key is wrong", key.serializePubB58(MAINNET), encoded); assertEquals("Depth of deserialized parentless public HD key is wrong", key.getDepth(), 3); assertEquals("Path size of deserialized parentless public HD key is wrong", key.getPath().size(), 1); assertEquals("Parent fingerprint of deserialized parentless public HD key is wrong", key.getParentFingerprint(), 0xbef5a2f9); // This encoding is the same key but including its private data: encoded = "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM"; key = DeterministicKey.deserializeB58(encoded, MAINNET); assertEquals("Reserialized parentless private HD key is wrong", key.serializePrivB58(MAINNET), encoded); assertEquals("Depth of deserialized parentless private HD key is wrong", key.getDepth(), 3); assertEquals("Path size of deserialized parentless private HD key is wrong", key.getPath().size(), 1); assertEquals("Parent fingerprint of deserialized parentless private HD key is wrong", key.getParentFingerprint(), 0xbef5a2f9); // These encodings are of the the root key of that hierarchy assertEquals("Parent fingerprint of root node public HD key should be zero", DeterministicKey.deserializeB58("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", MAINNET).getParentFingerprint(), 0); assertEquals("Parent fingerprint of root node private HD key should be zero", DeterministicKey.deserializeB58("xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", MAINNET).getParentFingerprint(), 0); } private static String hexEncodePub(DeterministicKey pubKey) { return ByteUtils.formatHex(pubKey.getPubKey()); } }
20,015
61.161491
401
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/EncodedPrivateKeyTest.java
/* * Copyright 2014 bitcoinj project * Copyright 2019 Tim Strasser * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.EncodedPrivateKey; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.junit.Test; public class EncodedPrivateKeyTest { @Test public void equalsContract() { EqualsVerifier.forClass(EncodedPrivateKey.class) .withPrefabValues(NetworkParameters.class, MainNetParams.get(), TestNet3Params.get()) .suppress(Warning.NULL_FIELDS) .suppress(Warning.TRANSIENT_FIELDS) .usingGetClass() .verify(); } }
1,353
33.717949
101
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/X509UtilsTest.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.junit.Test; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import static org.junit.Assert.assertEquals; public class X509UtilsTest { @Test public void testDisplayName() throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate clientCert = (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream( "startssl-client.crt")); assertEquals("Andreas Schildbach", X509Utils.getDisplayNameFromCertificate(clientCert, false)); X509Certificate comodoCert = (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream( "comodo-smime.crt")); assertEquals("comodo.com@schildbach.de", X509Utils.getDisplayNameFromCertificate(comodoCert, true)); } }
1,480
35.121951
109
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/KeyCrypterScryptTest.java
/* * Copyright 2013 Jim Burton. * Copyright 2014 Andreas Schildbach * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.internal.ByteUtils; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Random; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; public class KeyCrypterScryptTest { private static final Logger log = LoggerFactory.getLogger(KeyCrypterScryptTest.class); // Nonsense bytes for encryption test. private static final byte[] TEST_BYTES1 = {0, -101, 2, 103, -4, 105, 6, 107, 8, -109, 10, 111, -12, 113, 14, -115, 16, 117, -18, 119, 20, 121, 22, 123, -24, 125, 26, 127, -28, 29, -30, 31}; private static final int SCRYPT_ITERATIONS = 256; private static final CharSequence PASSWORD1 = "aTestPassword"; private static final CharSequence PASSWORD2 = "0123456789"; private static final CharSequence WRONG_PASSWORD = "thisIsTheWrongPassword"; private static final CharSequence WRONG_PASSWORD2 = "anotherWrongPassword"; private KeyCrypterScrypt keyCrypter; @Before public void setUp() { keyCrypter = new KeyCrypterScrypt(SCRYPT_ITERATIONS); } @Test public void testKeyCrypterGood1() { // Encrypt. EncryptedData data = keyCrypter.encrypt(TEST_BYTES1, keyCrypter.deriveKey(PASSWORD1)); assertNotNull(data); // Decrypt. byte[] reborn = keyCrypter.decrypt(data, keyCrypter.deriveKey(PASSWORD1)); log.debug("Original: " + ByteUtils.formatHex(TEST_BYTES1)); log.debug("Reborn : " + ByteUtils.formatHex(reborn)); assertEquals(ByteUtils.formatHex(TEST_BYTES1), ByteUtils.formatHex(reborn)); } /** * Test with random plain text strings and random passwords. * UUIDs are used and hence will only cover hex characters (and the separator hyphen). * @throws KeyCrypterException */ @Test public void testKeyCrypterGood2() { // Trying random UUIDs for plainText and passwords. int numberOfTests = 16; for (int i = 0; i < numberOfTests; i++) { // Create a UUID as the plaintext and use another for the password. String plainText = UUID.randomUUID().toString(); CharSequence password = UUID.randomUUID().toString(); EncryptedData data = keyCrypter.encrypt(plainText.getBytes(), keyCrypter.deriveKey(password)); assertNotNull(data); byte[] reconstructedPlainBytes = keyCrypter.decrypt(data,keyCrypter.deriveKey(password)); assertEquals(ByteUtils.formatHex(plainText.getBytes()), ByteUtils.formatHex(reconstructedPlainBytes)); } } @Test public void testKeyCrypterWrongPassword() { // create a longer encryption string StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100; i++) { builder.append(i).append(" The quick brown fox"); } byte[] plainText = builder.toString().getBytes(); EncryptedData data = keyCrypter.encrypt(plainText, keyCrypter.deriveKey(PASSWORD2)); assertNotNull(data); try { // This sometimes doesn't throw due to relying on padding... byte[] cipherText = keyCrypter.decrypt(data, keyCrypter.deriveKey(WRONG_PASSWORD)); // ...so we also check for length, because that's the 2nd level test we're doing e.g. in ECKey/DeterministicKey... assertNotEquals(plainText.length, cipherText.length); // ...and then try with another wrong password again. keyCrypter.decrypt(data, keyCrypter.deriveKey(WRONG_PASSWORD2)); // Note: it can still fail, but it should be extremely rare. fail("Decrypt with wrong password did not throw exception"); } catch (KeyCrypterException.InvalidCipherText x) { // expected } } @Test public void testEncryptDecryptBytes1() { // Encrypt bytes. EncryptedData data = keyCrypter.encrypt(TEST_BYTES1, keyCrypter.deriveKey(PASSWORD1)); assertNotNull(data); log.debug("\nEncrypterDecrypterTest: cipherBytes = \nlength = " + data.encryptedBytes.length + "\n---------------\n" + ByteUtils.formatHex(data.encryptedBytes) + "\n---------------\n"); byte[] rebornPlainBytes = keyCrypter.decrypt(data, keyCrypter.deriveKey(PASSWORD1)); log.debug("Original: " + ByteUtils.formatHex(TEST_BYTES1)); log.debug("Reborn1 : " + ByteUtils.formatHex(rebornPlainBytes)); assertEquals(ByteUtils.formatHex(TEST_BYTES1), ByteUtils.formatHex(rebornPlainBytes)); } @Test public void testEncryptDecryptBytes2() { // Encrypt random bytes of various lengths up to length 50. Random random = new Random(); for (int i = 0; i < 50; i++) { byte[] plainBytes = new byte[i]; random.nextBytes(plainBytes); EncryptedData data = keyCrypter.encrypt(plainBytes, keyCrypter.deriveKey(PASSWORD1)); assertNotNull(data); //log.debug("\nEncrypterDecrypterTest: cipherBytes = \nlength = " + cipherBytes.length + "\n---------------\n" + Utils.ByteUtils.formatHex(cipherBytes) + "\n---------------\n"); byte[] rebornPlainBytes = keyCrypter.decrypt(data, keyCrypter.deriveKey(PASSWORD1)); log.debug("Original: (" + i + ") " + ByteUtils.formatHex(plainBytes)); log.debug("Reborn1 : (" + i + ") " + ByteUtils.formatHex(rebornPlainBytes)); assertEquals(ByteUtils.formatHex(plainBytes), ByteUtils.formatHex(rebornPlainBytes)); } } }
6,344
41.019868
193
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/HDUtilsTest.java
/* * Copyright 2013 Matija Mazi * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.junit.Test; import org.bitcoinj.base.internal.ByteUtils; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class HDUtilsTest { @Test public void testHmac() { String[] tv = { "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" + "0b0b0b0b", "4869205468657265", "87aa7cdea5ef619d4ff0b4241a1d6cb0" + "2379f4e2ce4ec2787ad0b30545e17cde" + "daa833b7d6b8a702038b274eaea3f4e4" + "be9d914eeb61f1702e696c203a126854", "4a656665", "7768617420646f2079612077616e7420" + "666f72206e6f7468696e673f", "164b7a7bfcf819e2e395fbe73b56e0a3" + "87bd64222e831fd610270cd7ea250554" + "9758bf75c05a994a6d034f65f8f0e6fd" + "caeab1a34d4a6b4b636e070a38bce737", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaa", "dddddddddddddddddddddddddddddddd" + "dddddddddddddddddddddddddddddddd" + "dddddddddddddddddddddddddddddddd" + "dddd", "fa73b0089d56a284efb0f0756c890be9" + "b1b5dbdd8ee81a3655f83e33b2279d39" + "bf3e848279a722c806b485a47e67c807" + "b946a337bee8942674278859e13292fb", "0102030405060708090a0b0c0d0e0f10" + "111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcd", "b0ba465637458c6990e5a8c5f61d4af7" + "e576d97ff94b872de76f8050361ee3db" + "a91ca5c11aa25eb4d679275cc5788063" + "a5f19741120c4f2de2adebeb10a298dd", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa", "54657374205573696e67204c61726765" + "72205468616e20426c6f636b2d53697a" + "65204b6579202d2048617368204b6579" + "204669727374", "80b24263c7c1a3ebb71493c1dd7be8b4" + "9b46d1f41b4aeec1121b013783f8f352" + "6b56d037e05f2598bd0fd2215d6a1e52" + "95e64f73f63f0aec8b915a985d786598", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa", "54686973206973206120746573742075" + "73696e672061206c6172676572207468" + "616e20626c6f636b2d73697a65206b65" + "7920616e642061206c61726765722074" + "68616e20626c6f636b2d73697a652064" + "6174612e20546865206b6579206e6565" + "647320746f2062652068617368656420" + "6265666f7265206265696e6720757365" + "642062792074686520484d414320616c" + "676f726974686d2e", "e37b6a775dc87dbaa4dfa9f96e5e3ffd" + "debd71f8867289865df5a32d20cdc944" + "b6022cac3c4982b10d5eeb55c3e4de15" + "134676fb6de0446065c97440fa8c6a58" }; for (int i = 0; i < tv.length; i += 3) { assertArrayEquals("Case " + i, getBytes(tv, i + 2), HDUtils.hmacSha512(getBytes(tv, i), getBytes(tv, i + 1))); } } private static byte[] getBytes(String[] hmacTestVectors, int i) { return ByteUtils.parseHex(hmacTestVectors[i]); } @Test public void testLongToByteArray() { byte[] bytes = HDUtils.longTo4ByteArray(1026); assertEquals("00000402", ByteUtils.formatHex(bytes)); } }
5,527
42.873016
122
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/BIP32Test.java
/* * Copyright 2013 Matija Mazi. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.Base58; import static org.bitcoinj.base.BitcoinNetwork.MAINNET; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.bitcoinj.base.internal.ByteUtils; import static org.junit.Assert.assertEquals; /** * A test with test vectors as per BIP 32 spec: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Test_Vectors */ public class BIP32Test { private static final Logger log = LoggerFactory.getLogger(BIP32Test.class); HDWTestVector[] tvs = { new HDWTestVector( "000102030405060708090a0b0c0d0e0f", "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8", Arrays.asList( new HDWTestVector.DerivedTestCase( "Test1 m/0H", HDPath.m(new ChildNumber(0, true)), "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw" ), new HDWTestVector.DerivedTestCase( "Test1 m/0H/1", HDPath.m(new ChildNumber(0, true), new ChildNumber(1, false)), "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ" ), new HDWTestVector.DerivedTestCase( "Test1 m/0H/1/2H", HDPath.m(new ChildNumber(0, true), new ChildNumber(1, false), new ChildNumber(2, true)), "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5" ), new HDWTestVector.DerivedTestCase( "Test1 m/0H/1/2H/2", HDPath.m(new ChildNumber(0, true), new ChildNumber(1, false), new ChildNumber(2, true), new ChildNumber(2, false)), "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV" ), new HDWTestVector.DerivedTestCase( "Test1 m/0H/1/2H/2/1000000000", HDPath.m(new ChildNumber(0, true), new ChildNumber(1, false), new ChildNumber(2, true), new ChildNumber(2, false), new ChildNumber(1000000000, false)), "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy" ) ) ), new HDWTestVector( "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", Arrays.asList( new HDWTestVector.DerivedTestCase( "Test2 m/0", HDPath.m(new ChildNumber(0, false)), "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH" ), new HDWTestVector.DerivedTestCase( "Test2 m/0/2147483647H", HDPath.m(new ChildNumber(0, false), new ChildNumber(2147483647, true)), "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a" ), new HDWTestVector.DerivedTestCase( "Test2 m/0/2147483647H/1", HDPath.m(new ChildNumber(0, false), new ChildNumber(2147483647, true), new ChildNumber(1, false)), "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon" ), new HDWTestVector.DerivedTestCase( "Test2 m/0/2147483647H/1/2147483646H", HDPath.m(new ChildNumber(0, false), new ChildNumber(2147483647, true), new ChildNumber(1, false), new ChildNumber(2147483646, true)), "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL" ), new HDWTestVector.DerivedTestCase( "Test2 m/0/2147483647H/1/2147483646H/2", HDPath.m(new ChildNumber(0, false), new ChildNumber(2147483647, true), new ChildNumber(1, false), new ChildNumber(2147483646, true), new ChildNumber(2, false)), "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt" ) ) ), new HDWTestVector( "4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be", "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6", "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13", Arrays.asList( new HDWTestVector.DerivedTestCase( "Test3 m/0H", HDPath.m(new ChildNumber(0, true)), "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L", "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y" ) ) ), new HDWTestVector( "3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678", "xprv9s21ZrQH143K48vGoLGRPxgo2JNkJ3J3fqkirQC2zVdk5Dgd5w14S7fRDyHH4dWNHUgkvsvNDCkvAwcSHNAQwhwgNMgZhLtQC63zxwhQmRv", "xpub661MyMwAqRbcGczjuMoRm6dXaLDEhW1u34gKenbeYqAix21mdUKJyuyu5F1rzYGVxyL6tmgBUAEPrEz92mBXjByMRiJdba9wpnN37RLLAXa", Arrays.asList( new HDWTestVector.DerivedTestCase( "Test4 m/0H", HDPath.m(new ChildNumber(0, true)), "xprv9vB7xEWwNp9kh1wQRfCCQMnZUEG21LpbR9NPCNN1dwhiZkjjeGRnaALmPXCX7SgjFTiCTT6bXes17boXtjq3xLpcDjzEuGLQBM5ohqkao9G", "xpub69AUMk3qDBi3uW1sXgjCmVjJ2G6WQoYSnNHyzkmdCHEhSZ4tBok37xfFEqHd2AddP56Tqp4o56AePAgCjYdvpW2PU2jbUPFKsav5ut6Ch1m" ), new HDWTestVector.DerivedTestCase( "Test4 m/0H/1H", HDPath.m(new ChildNumber(0, true), new ChildNumber(1, true)), "xprv9xJocDuwtYCMNAo3Zw76WENQeAS6WGXQ55RCy7tDJ8oALr4FWkuVoHJeHVAcAqiZLE7Je3vZJHxspZdFHfnBEjHqU5hG1Jaj32dVoS6XLT1", "xpub6BJA1jSqiukeaesWfxe6sNK9CCGaujFFSJLomWHprUL9DePQ4JDkM5d88n49sMGJxrhpjazuXYWdMf17C9T5XnxkopaeS7jGk1GyyVziaMt" ) ) ) }; @Test public void testVector1() { testVector(0); } @Test public void testVector2() { testVector(1); } @Test public void testVector3() { testVector(2); } @Test public void testVector4() { testVector(3); } private void testVector(int testCase) { log.info("======= Test vector {}", testCase); HDWTestVector tv = tvs[testCase]; DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(ByteUtils.parseHex(tv.seed)); assertEquals(testEncode(tv.priv), testEncode(masterPrivateKey.serializePrivB58(MAINNET))); assertEquals(testEncode(tv.pub), testEncode(masterPrivateKey.serializePubB58(MAINNET))); DeterministicHierarchy dh = new DeterministicHierarchy(masterPrivateKey); for (int i = 0; i < tv.derived.size(); i++) { HDWTestVector.DerivedTestCase tc = tv.derived.get(i); log.info("{}", tc.name); assertEquals(tc.name, String.format(Locale.US, "Test%d %s", testCase + 1, tc.path)); int depth = tc.path.size() - 1; DeterministicKey ehkey = dh.deriveChild(tc.path.subList(0, depth), false, true, tc.path.get(depth)); assertEquals(testEncode(tc.priv), testEncode(ehkey.serializePrivB58(MAINNET))); assertEquals(testEncode(tc.pub), testEncode(ehkey.serializePubB58(MAINNET))); } } private String testEncode(String what) { return ByteUtils.formatHex(Base58.decodeChecked(what)); } static class HDWTestVector { final String seed; final String priv; final String pub; final List<DerivedTestCase> derived; HDWTestVector(String seed, String priv, String pub, List<DerivedTestCase> derived) { this.seed = seed; this.priv = priv; this.pub = pub; this.derived = derived; } static class DerivedTestCase { final String name; final HDPath path; final String pub; final String priv; DerivedTestCase(String name, HDPath path, String priv, String pub) { this.name = name; this.path = path; this.pub = pub; this.priv = priv; } } } }
13,006
58.392694
196
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/MnemonicCodeTest.java
/* * Copyright 2013 Ken Sedgwick * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.bitcoinj.base.internal.ByteUtils; import static org.bitcoinj.base.internal.InternalUtils.WHITESPACE_SPLITTER; import static org.junit.Assert.assertEquals; /** * Test the various guard clauses of {@link MnemonicCode}. * * See {@link MnemonicCodeVectorsTest} test vectors. */ public class MnemonicCodeTest { private MnemonicCode mc; @Before public void setup() throws IOException { mc = new MnemonicCode(); } @Test public void testGetWordList() { List<String> wordList = mc.getWordList(); assertEquals(2048, wordList.size()); assertEquals("abandon", wordList.get(0)); assertEquals("zoo", wordList.get(2047)); } @Test(expected = UnsupportedOperationException.class) public void testGetWordListUnmodifiable() { List<String> wordList = mc.getWordList(); wordList.remove(0); } @Test(expected = RuntimeException.class) public void testBadEntropyLength() throws Exception { byte[] entropy = ByteUtils.parseHex("7f7f7f7f7f7f7f7f7f7f7f7f7f7f"); mc.toMnemonic(entropy); } @Test(expected = MnemonicException.MnemonicLengthException.class) public void testBadLength() throws Exception { List<String> words = WHITESPACE_SPLITTER.splitToList("risk tiger venture dinner age assume float denial penalty hello"); mc.check(words); } @Test(expected = MnemonicException.MnemonicWordException.class) public void testBadWord() throws Exception { List<String> words = WHITESPACE_SPLITTER.splitToList("risk tiger venture dinner xyzzy assume float denial penalty hello game wing"); mc.check(words); } @Test(expected = MnemonicException.MnemonicChecksumException.class) public void testBadChecksum() throws Exception { List<String> words = WHITESPACE_SPLITTER.splitToList("bless cloud wheel regular tiny venue bird web grief security dignity zoo"); mc.check(words); } @Test(expected = MnemonicException.MnemonicLengthException.class) public void testEmptyMnemonic() throws Exception { List<String> words = new ArrayList<>(); mc.check(words); } @Test(expected = RuntimeException.class) public void testEmptyEntropy() throws Exception { byte[] entropy = {}; mc.toMnemonic(entropy); } @Test(expected = NullPointerException.class) public void testNullPassphrase() { List<String> code = WHITESPACE_SPLITTER.splitToList("legal winner thank year wave sausage worth useful legal winner thank yellow"); MnemonicCode.toSeed(code, null); } }
3,421
32.223301
140
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/BIP38PrivateKeyTest.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.Base58; import org.bitcoinj.crypto.BIP38PrivateKey.BadPassphraseException; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.bitcoinj.base.BitcoinNetwork.MAINNET; import static org.bitcoinj.base.BitcoinNetwork.TESTNET; public class BIP38PrivateKeyTest { @Test public void bip38testvector_noCompression_noEcMultiply_test1() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg"); ECKey key = encryptedKey.decrypt("TestingOneTwoThree"); assertEquals("5KN7MzqK5wt2TP1fQCYyHBtDrXdJuXbUzm4A9rKAteGu3Qi5CVR", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_noCompression_noEcMultiply_test2() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq"); ECKey key = encryptedKey.decrypt("Satoshi"); assertEquals("5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_noCompression_noEcMultiply_test3() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"); StringBuilder passphrase = new StringBuilder(); passphrase.appendCodePoint(0x03d2); // GREEK UPSILON WITH HOOK passphrase.appendCodePoint(0x0301); // COMBINING ACUTE ACCENT passphrase.appendCodePoint(0x0000); // NULL passphrase.appendCodePoint(0x010400); // DESERET CAPITAL LETTER LONG I passphrase.appendCodePoint(0x01f4a9); // PILE OF POO ECKey key = encryptedKey.decrypt(passphrase.toString()); assertEquals("5Jajm8eQ22H3pGWLEVCXyvND8dQZhiQhoLJNKjYXk9roUFTMSZ4", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_compression_noEcMultiply_test1() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo"); ECKey key = encryptedKey.decrypt("TestingOneTwoThree"); assertEquals("L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_compression_noEcMultiply_test2() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7"); ECKey key = encryptedKey.decrypt("Satoshi"); assertEquals("KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_ecMultiply_noCompression_noLotAndSequence_test1() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PfQu77ygVyJLZjfvMLyhLMQbYnu5uguoJJ4kMCLqWwPEdfpwANVS76gTX"); ECKey key = encryptedKey.decrypt("TestingOneTwoThree"); assertEquals("5K4caxezwjGCGfnoPTZ8tMcJBLB7Jvyjv4xxeacadhq8nLisLR2", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_ecMultiply_noCompression_noLotAndSequence_test2() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PfLGnQs6VZnrNpmVKfjotbnQuaJK4KZoPFrAjx1JMJUa1Ft8gnf5WxfKd"); ECKey key = encryptedKey.decrypt("Satoshi"); assertEquals("5KJ51SgxWaAYR13zd9ReMhJpwrcX47xTJh2D3fGPG9CM8vkv5sH", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_ecMultiply_noCompression_lotAndSequence_test1() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PgNBNNzDkKdhkT6uJntUXwwzQV8Rr2tZcbkDcuC9DZRsS6AtHts4Ypo1j"); ECKey key = encryptedKey.decrypt("MOLON LABE"); assertEquals("5JLdxTtcTHcfYcmJsNVy1v2PMDx432JPoYcBTVVRHpPaxUrdtf8", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bip38testvector_ecMultiply_noCompression_lotAndSequence_test2() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PgGWtx25kUg8QWvwuJAgorN6k9FbE25rv5dMRwu5SKMnfpfVe5mar2ngH"); ECKey key = encryptedKey.decrypt("ΜΟΛΩΝ ΛΑΒΕ"); assertEquals("5KMKKuUmAkiNbA3DazMQiLfDq47qs8MAEThm4yL8R2PhV1ov33D", key.getPrivateKeyEncoded(MAINNET) .toString()); } @Test public void bitcoinpaperwallet_testnet() throws Exception { // values taken from bitcoinpaperwallet.com BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(BitcoinNetwork.TESTNET, "6PRPhQhmtw6dQu6jD8E1KS4VphwJxBS9Eh9C8FQELcrwN3vPvskv9NKvuL"); ECKey key = encryptedKey.decrypt("password"); assertEquals("93MLfjbY6ugAsLeQfFY6zodDa8izgm1XAwA9cpMbUTwLkDitopg", key.getPrivateKeyEncoded(TESTNET) .toString()); } @Test public void bitaddress_testnet() throws Exception { // values taken from bitaddress.org BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(BitcoinNetwork.TESTNET, "6PfMmVHn153N3x83Yiy4Nf76dHUkXufe2Adr9Fw5bewrunGNeaw2QCpifb"); ECKey key = encryptedKey.decrypt("password"); assertEquals("91tCpdaGr4Khv7UAuUxa6aMqeN5GcPVJxzLtNsnZHTCndxkRcz2", key.getPrivateKeyEncoded(TESTNET) .toString()); } @Test(expected = BadPassphraseException.class) public void badPassphrase() throws Exception { BIP38PrivateKey encryptedKey = BIP38PrivateKey.fromBase58(MAINNET, "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg"); encryptedKey.decrypt("BAD"); } @Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBase58_invalidLength() { String base58 = Base58.encodeChecked(1, new byte[16]); BIP38PrivateKey.fromBase58((Network) null, base58); } @Test public void roundtripBase58() { String base58 = "6PfMmVHn153N3x83Yiy4Nf76dHUkXufe2Adr9Fw5bewrunGNeaw2QCpifb"; assertEquals(base58, BIP38PrivateKey.fromBase58(MAINNET, base58).toBase58()); } }
7,376
45.396226
110
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/HDKeyDerivationTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.HDKeyDerivation.PublicDeriveMode; import org.junit.Test; import java.math.BigInteger; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author Andreas Schildbach */ public class HDKeyDerivationTest { private static final KeyCrypterScrypt KEY_CRYPTER = new KeyCrypterScrypt(2); private static final AesKey AES_KEY = KEY_CRYPTER.deriveKey("password"); private static final ChildNumber CHILD_NUMBER = ChildNumber.ONE; private static final String EXPECTED_CHILD_CHAIN_CODE = "c4341fe988a2ae6240788c6b21df268b9286769915bed23c7649f263b3643ee8"; private static final String EXPECTED_CHILD_PRIVATE_KEY = "48516d403070bc93f5e4d78c984cf2d71fc9799293b4eeb3de4f88e3892f523d"; private static final String EXPECTED_CHILD_PUBLIC_KEY = "036d27f617ce7b0cbdce0abebd1c7aafc147bd406276e6a08d64d7a7ed0ca68f0e"; @Test public void testDeriveFromPrivateParent() { DeterministicKey parent = new DeterministicKey(HDPath.M(), new byte[32], BigInteger.TEN, null); assertFalse(parent.isPubKeyOnly()); assertFalse(parent.isEncrypted()); DeterministicKey fromPrivate = HDKeyDerivation.deriveChildKeyFromPrivate(parent, CHILD_NUMBER); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPrivate.getChainCode())); assertEquals(EXPECTED_CHILD_PRIVATE_KEY, fromPrivate.getPrivateKeyAsHex()); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPrivate.getPublicKeyAsHex()); assertFalse(fromPrivate.isPubKeyOnly()); assertFalse(fromPrivate.isEncrypted()); DeterministicKey fromPublic = HDKeyDerivation.deriveChildKeyFromPublic(parent, CHILD_NUMBER, PublicDeriveMode.NORMAL); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublic.getChainCode())); assertEquals(EXPECTED_CHILD_PRIVATE_KEY, fromPublic.getPrivateKeyAsHex()); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublic.getPublicKeyAsHex()); assertFalse(fromPublic.isPubKeyOnly()); assertFalse(fromPublic.isEncrypted()); DeterministicKey fromPublicWithInversion = HDKeyDerivation.deriveChildKeyFromPublic(parent, CHILD_NUMBER, PublicDeriveMode.WITH_INVERSION); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublicWithInversion.getChainCode())); assertEquals(EXPECTED_CHILD_PRIVATE_KEY, fromPublicWithInversion.getPrivateKeyAsHex()); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublicWithInversion.getPublicKeyAsHex()); assertFalse(fromPublicWithInversion.isPubKeyOnly()); assertFalse(fromPublicWithInversion.isEncrypted()); } @Test public void testDeriveFromPublicParent() { DeterministicKey parent = new DeterministicKey(HDPath.M(), new byte[32], BigInteger.TEN, null).dropPrivateBytes(); assertTrue(parent.isPubKeyOnly()); assertFalse(parent.isEncrypted()); try { HDKeyDerivation.deriveChildKeyFromPrivate(parent, CHILD_NUMBER); fail(); } catch (IllegalArgumentException x) { // expected } DeterministicKey fromPublic = HDKeyDerivation.deriveChildKeyFromPublic(parent, CHILD_NUMBER, PublicDeriveMode.NORMAL); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublic.getChainCode())); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublic.getPublicKeyAsHex()); assertTrue(fromPublic.isPubKeyOnly()); assertFalse(fromPublic.isEncrypted()); DeterministicKey fromPublicWithInversion = HDKeyDerivation.deriveChildKeyFromPublic(parent, CHILD_NUMBER, PublicDeriveMode.WITH_INVERSION); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublicWithInversion.getChainCode())); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublicWithInversion.getPublicKeyAsHex()); assertTrue(fromPublicWithInversion.isPubKeyOnly()); assertFalse(fromPublicWithInversion.isEncrypted()); } @Test public void testDeriveFromEncryptedParent() { DeterministicKey parent = new DeterministicKey(HDPath.M(), new byte[32], BigInteger.TEN, null); parent = parent.encrypt(KEY_CRYPTER, AES_KEY, null); assertTrue(parent.isEncrypted()); assertTrue(parent.isPubKeyOnly()); try { HDKeyDerivation.deriveChildKeyFromPrivate(parent, CHILD_NUMBER); fail(); } catch (IllegalArgumentException x) { // expected } DeterministicKey fromPublic = HDKeyDerivation.deriveChildKeyFromPublic(parent, CHILD_NUMBER, PublicDeriveMode.NORMAL); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublic.getChainCode())); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublic.getPublicKeyAsHex()); assertTrue(fromPublic.isPubKeyOnly()); assertTrue(fromPublic.isEncrypted()); fromPublic = fromPublic.decrypt(AES_KEY); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublic.getChainCode())); assertEquals(EXPECTED_CHILD_PRIVATE_KEY, fromPublic.getPrivateKeyAsHex()); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublic.getPublicKeyAsHex()); DeterministicKey fromPublicWithInversion = HDKeyDerivation.deriveChildKeyFromPublic(parent, CHILD_NUMBER, PublicDeriveMode.WITH_INVERSION); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublicWithInversion.getChainCode())); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublicWithInversion.getPublicKeyAsHex()); assertTrue(fromPublicWithInversion.isPubKeyOnly()); assertTrue(fromPublicWithInversion.isEncrypted()); fromPublicWithInversion = fromPublicWithInversion.decrypt(AES_KEY); assertEquals(EXPECTED_CHILD_CHAIN_CODE, ByteUtils.formatHex(fromPublicWithInversion.getChainCode())); assertEquals(EXPECTED_CHILD_PRIVATE_KEY, fromPublicWithInversion.getPrivateKeyAsHex()); assertEquals(EXPECTED_CHILD_PUBLIC_KEY, fromPublicWithInversion.getPublicKeyAsHex()); } @Test public void testGenerate() { DeterministicKey parent = new DeterministicKey(HDPath.m(), new byte[32], BigInteger.TEN, null); assertFalse(parent.isPubKeyOnly()); assertFalse(parent.isEncrypted()); List<DeterministicKey> keys0 = HDKeyDerivation.generate(parent, CHILD_NUMBER.num()) .limit(0) .collect(Collectors.toList()); assertEquals(0, keys0.size()); List<DeterministicKey> keys1 = HDKeyDerivation.generate(parent, CHILD_NUMBER.num()) .limit(1) .collect(Collectors.toList()); assertEquals(1, keys1.size()); assertEquals(HDPath.m(CHILD_NUMBER), keys1.get(0).getPath()); List<DeterministicKey> keys2 = HDKeyDerivation.generate(parent, CHILD_NUMBER.num()) .limit(2) .collect(Collectors.toList()); assertEquals(2, keys2.size()); assertEquals(HDPath.parsePath("m/1"), keys2.get(0).getPath()); assertEquals(HDPath.parsePath("m/2"), keys2.get(1).getPath()); } }
8,373
48.845238
129
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/DumpedPrivateKeyTest.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.Base58; import org.bitcoinj.base.Network; import org.bitcoinj.base.exceptions.AddressFormatException; import static org.bitcoinj.base.BitcoinNetwork.MAINNET; import static org.bitcoinj.base.BitcoinNetwork.TESTNET; import org.bitcoinj.core.NetworkParameters; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; public class DumpedPrivateKeyTest { @Test public void checkNetwork() { DumpedPrivateKey.fromBase58(MAINNET, "5HtUCLMFWNueqN9unpgX2DzjMg6SDNZyKRb8s3LJgpFg5ubuMrk"); } @Test(expected = AddressFormatException.WrongNetwork.class) public void checkNetworkWrong() { DumpedPrivateKey.fromBase58(TESTNET, "5HtUCLMFWNueqN9unpgX2DzjMg6SDNZyKRb8s3LJgpFg5ubuMrk"); } @Test public void roundtripBase58() { String base58 = "5HtUCLMFWNueqN9unpgX2DzjMg6SDNZyKRb8s3LJgpFg5ubuMrk"; // 32-bytes key DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58((Network) null, base58); assertFalse(dumpedPrivateKey.isPubKeyCompressed()); assertEquals(base58, dumpedPrivateKey.toBase58()); } @Test public void roundtripBase58_compressed() { String base58 = "cSthBXr8YQAexpKeh22LB9PdextVE1UJeahmyns5LzcmMDSy59L4"; // 33-bytes, compressed == true DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58((Network) null, base58); assertTrue(dumpedPrivateKey.isPubKeyCompressed()); assertEquals(base58, dumpedPrivateKey.toBase58()); } @Test(expected = AddressFormatException.class) public void roundtripBase58_invalidCompressed() { String base58 = "5Kg5shEQWrf1TojaHTdc2kLuz5Mfh4uvp3cYu8uJHaHgfTGUbTD"; // 32-bytes key byte[] bytes = Base58.decodeChecked(base58); bytes = Arrays.copyOf(bytes, bytes.length + 1); // append a "compress" byte bytes[bytes.length - 1] = 0; // set it to false base58 = Base58.encode(bytes); // 33-bytes key, compressed == false DumpedPrivateKey.fromBase58((Network) null, base58); // fail } @Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBase58_tooShort() { String base58 = Base58.encodeChecked(NetworkParameters.of(MAINNET).getDumpedPrivateKeyHeader(), new byte[31]); DumpedPrivateKey.fromBase58((Network) null, base58); } @Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBase58_tooLong() { String base58 = Base58.encodeChecked(NetworkParameters.of(MAINNET).getDumpedPrivateKeyHeader(), new byte[34]); DumpedPrivateKey.fromBase58((Network) null, base58); } @Test public void roundtripBase58_getKey() { ECKey k = new ECKey().decompress(); assertFalse(k.isCompressed()); assertEquals(k.getPrivKey(), DumpedPrivateKey.fromBase58((Network) null, k.getPrivateKeyAsWiF(MAINNET)).getKey().getPrivKey()); } @Test public void roundtripBase58_compressed_getKey() { ECKey k = new ECKey(); assertTrue(k.isCompressed()); assertEquals(k.getPrivKey(), DumpedPrivateKey.fromBase58((Network) null, k.getPrivateKeyAsWiF(MAINNET)).getKey().getPrivKey()); } }
4,021
39.22
118
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/ECKeyTest.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import com.google.common.collect.Lists; import com.google.common.primitives.Bytes; import org.bitcoinj.base.Address; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.SegwitAddress; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.ECKey.ECDSASignature; import org.bitcoinj.crypto.internal.CryptoUtils; import org.bitcoinj.base.internal.FutureUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.math.BigInteger; import java.security.SignatureException; import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.bitcoinj.base.internal.ByteUtils.reverseBytes; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.bitcoinj.base.BitcoinNetwork.MAINNET; import static org.bitcoinj.base.BitcoinNetwork.TESTNET; public class ECKeyTest { private static final Logger log = LoggerFactory.getLogger(ECKeyTest.class); private KeyCrypter keyCrypter; private static final int SCRYPT_ITERATIONS = 256; private static CharSequence PASSWORD1 = "my hovercraft has eels"; private static CharSequence WRONG_PASSWORD = "it is a snowy day today"; @Before public void setUp() { keyCrypter = new KeyCrypterScrypt(SCRYPT_ITERATIONS); } @Test public void sValue() { // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability // issue that can allow someone to change a transaction [hash] without invalidating the signature. final byte ITERATIONS = 10; final ECKey key = new ECKey(); Function<Byte, ECKey.ECDSASignature> signer = b -> key.sign(Sha256Hash.of(new byte[]{b})); Function<Byte, CompletableFuture<ECKey.ECDSASignature>> asyncSigner = b -> CompletableFuture.supplyAsync(() -> signer.apply(b)); List<CompletableFuture<ECKey.ECDSASignature>> sigFutures = IntStream.range(0, ITERATIONS) .mapToObj(i -> (byte) i) .map(asyncSigner) .collect(Collectors.toList()); List<ECKey.ECDSASignature> sigs = FutureUtils.allAsList(sigFutures).join(); for (ECKey.ECDSASignature signature : sigs) { assertTrue(signature.isCanonical()); } final ECDSASignature first = sigs.get(0); final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(first.r, first.s); assertEquals(first, duplicate); assertEquals(first.hashCode(), duplicate.hashCode()); final ECKey.ECDSASignature highS = new ECKey.ECDSASignature(first.r, ECKey.CURVE.getN().subtract(first.s)); assertFalse(highS.isCanonical()); } @Test public void testSignatures() throws Exception { // Test that we can construct an ECKey from a private key (deriving the public from the private), then signing // a message with it. BigInteger privkey = ByteUtils.bytesToBigInteger(ByteUtils.parseHex("180cb41c7c600be951b5d3d0a7334acc7506173875834f7a6c4c786a28fcbb19")); ECKey key = ECKey.fromPrivate(privkey); byte[] output = key.sign(Sha256Hash.ZERO_HASH).encodeToDER(); assertTrue(key.verify(Sha256Hash.ZERO_HASH.getBytes(), output)); // Test interop with a signature from elsewhere. byte[] sig = ByteUtils.parseHex( "3046022100dffbc26774fc841bbe1c1362fd643609c6e42dcb274763476d87af2c0597e89e022100c59e3c13b96b316cae9fa0ab0260612c7a133a6fe2b3445b6bf80b3123bf274d"); assertTrue(key.verify(Sha256Hash.ZERO_HASH.getBytes(), sig)); } @Test public void testASN1Roundtrip() throws Exception { byte[] privkeyASN1 = ByteUtils.parseHex( "3082011302010104205c0b98e524ad188ddef35dc6abba13c34a351a05409e5d285403718b93336a4aa081a53081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a144034200042af7a2aafe8dafd7dc7f9cfb58ce09bda7dce28653ab229b98d1d3d759660c672dd0db18c8c2d76aa470448e876fc2089ab1354c01a6e72cefc50915f4a963ee"); ECKey decodedKey = ECKey.fromASN1(privkeyASN1); // Now re-encode and decode the ASN.1 to see if it is equivalent (it does not produce the exact same byte // sequence, some integers are padded now). ECKey roundtripKey = ECKey.fromASN1(decodedKey.toASN1()); assertArrayEquals(decodedKey.getPrivKeyBytes(), roundtripKey.getPrivKeyBytes()); for (ECKey key : new ECKey[] {decodedKey, roundtripKey}) { byte[] message = reverseBytes(ByteUtils.parseHex( "11da3761e86431e4a54c176789e41f1651b324d240d599a7067bee23d328ec2a")); byte[] output = key.sign(Sha256Hash.wrap(message)).encodeToDER(); assertTrue(key.verify(message, output)); output = ByteUtils.parseHex( "304502206faa2ebc614bf4a0b31f0ce4ed9012eb193302ec2bcaccc7ae8bb40577f47549022100c73a1a1acc209f3f860bf9b9f5e13e9433db6f8b7bd527a088a0e0cd0a4c83e9"); assertTrue(key.verify(message, output)); } // Try to sign with one key and verify with the other. byte[] message = reverseBytes(ByteUtils.parseHex( "11da3761e86431e4a54c176789e41f1651b324d240d599a7067bee23d328ec2a")); assertTrue(roundtripKey.verify(message, decodedKey.sign(Sha256Hash.wrap(message)).encodeToDER())); assertTrue(decodedKey.verify(message, roundtripKey.sign(Sha256Hash.wrap(message)).encodeToDER())); } @Test public void testKeyPairRoundtrip() throws Exception { byte[] privkeyASN1 = ByteUtils.parseHex( "3082011302010104205c0b98e524ad188ddef35dc6abba13c34a351a05409e5d285403718b93336a4aa081a53081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101a144034200042af7a2aafe8dafd7dc7f9cfb58ce09bda7dce28653ab229b98d1d3d759660c672dd0db18c8c2d76aa470448e876fc2089ab1354c01a6e72cefc50915f4a963ee"); ECKey decodedKey = ECKey.fromASN1(privkeyASN1); // Now re-encode and decode the ASN.1 to see if it is equivalent (it does not produce the exact same byte // sequence, some integers are padded now). ECKey roundtripKey = ECKey.fromPrivateAndPrecalculatedPublic(decodedKey.getPrivKey(), decodedKey.getPubKeyPoint(), decodedKey.isCompressed()); for (ECKey key : new ECKey[] {decodedKey, roundtripKey}) { byte[] message = reverseBytes(ByteUtils.parseHex( "11da3761e86431e4a54c176789e41f1651b324d240d599a7067bee23d328ec2a")); byte[] output = key.sign(Sha256Hash.wrap(message)).encodeToDER(); assertTrue(key.verify(message, output)); output = ByteUtils.parseHex( "304502206faa2ebc614bf4a0b31f0ce4ed9012eb193302ec2bcaccc7ae8bb40577f47549022100c73a1a1acc209f3f860bf9b9f5e13e9433db6f8b7bd527a088a0e0cd0a4c83e9"); assertTrue(key.verify(message, output)); } // Try to sign with one key and verify with the other. byte[] message = reverseBytes(ByteUtils.parseHex( "11da3761e86431e4a54c176789e41f1651b324d240d599a7067bee23d328ec2a")); assertTrue(roundtripKey.verify(message, decodedKey.sign(Sha256Hash.wrap(message)).encodeToDER())); assertTrue(decodedKey.verify(message, roundtripKey.sign(Sha256Hash.wrap(message)).encodeToDER())); // Verify bytewise equivalence of public keys (i.e. compression state is preserved) ECKey key = new ECKey(); ECKey key2 = ECKey.fromASN1(key.toASN1()); assertArrayEquals(key.getPubKey(), key2.getPubKey()); } @Test public void base58Encoding() { String addr = "mqAJmaxMcG5pPHHc3H3NtyXzY7kGbJLuMF"; String privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD"; ECKey key = DumpedPrivateKey.fromBase58(TESTNET, privkey).getKey(); assertEquals(privkey, key.getPrivateKeyEncoded(TESTNET).toString()); assertEquals(addr, key.toAddress(ScriptType.P2PKH, TESTNET).toString()); } @Test public void createP2PKAddress() { String addr = "mqAJmaxMcG5pPHHc3H3NtyXzY7kGbJLuMF"; String privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD"; ECKey key = DumpedPrivateKey.fromBase58(TESTNET, privkey).getKey(); Address address = key.toAddress(ScriptType.P2PKH, TESTNET); assertTrue(address instanceof LegacyAddress); assertEquals(addr, address.toString()); } @Test public void createP2WPKAddress() { String addr = "tb1q0yy3juscd3zfavw76g4h3eqdqzda7qyf7pcpwg"; ECKey key = ECKey.fromPrivate( ByteUtils.parseHex("eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf")); assertEquals("03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873", key.getPublicKeyAsHex()); Address address = key.toAddress(ScriptType.P2WPKH, TESTNET); assertTrue(address instanceof SegwitAddress); assertEquals(((SegwitAddress) address).getWitnessVersion(), 0); assertEquals(addr, address.toString()); } @Test @Ignore("Can't create Taproot addresses from keys yet") public void createP2TRAddress() { String addr = "TBD"; ECKey key = ECKey.fromPrivate( ByteUtils.parseHex("eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf")); assertEquals("03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873", key.getPublicKeyAsHex()); Address address = key.toAddress(ScriptType.P2TR, TESTNET); assertTrue(address instanceof SegwitAddress); assertEquals(((SegwitAddress) address).getWitnessVersion(), 1); assertEquals(addr, address.toString()); } @Test public void base58Encoding_leadingZero() { String privkey = "91axuYLa8xK796DnBXXsMbjuc8pDYxYgJyQMvFzrZ6UfXaGYuqL"; ECKey key = DumpedPrivateKey.fromBase58(TESTNET, privkey).getKey(); assertEquals(privkey, key.getPrivateKeyEncoded(TESTNET).toString()); assertEquals(0, key.getPrivKeyBytes()[0]); } @Test public void base58Encoding_stress() { // Replace the loop bound with 1000 to get some keys with leading zero byte for (int i = 0 ; i < 20 ; i++) { ECKey key = new ECKey(); ECKey key1 = DumpedPrivateKey.fromBase58(TESTNET, key.getPrivateKeyEncoded(TESTNET).toString()).getKey(); assertEquals(ByteUtils.formatHex(key.getPrivKeyBytes()), ByteUtils.formatHex(key1.getPrivKeyBytes())); } } @Test public void signTextMessage() throws Exception { ECKey key = new ECKey(); String message = "聡中本"; String signatureBase64 = key.signMessage(message); log.info("Message signed with " + key.toAddress(ScriptType.P2PKH, MAINNET) + ": " + signatureBase64); // Should verify correctly. key.verifyMessage(message, signatureBase64); try { key.verifyMessage("Evil attacker says hello!", signatureBase64); fail(); } catch (SignatureException e) { // OK. } } @Test public void verifyMessageSignedWithCompressedP2PKHaddress() throws Exception { // Test vector generated by Bitcoin-Qt. String message = "hello"; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; Address expectedAddress = LegacyAddress.fromBase58("14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag", MAINNET); ECKey key = ECKey.signedMessageToKey(message, sigBase64); Address gotAddress = key.toAddress(ScriptType.P2PKH, MAINNET); assertEquals(expectedAddress, gotAddress); } @Test public void verifyMessageSignedWithUncompressedP2PKHaddress() throws Exception { String message = "message signed using an p2pkh address derived from an uncompressed public key"; String sigBase64 = "HDoME2gqLJApQTOLnce4J7BZcO1yIxUSP6tdKIUBLO99E+BH3uABshRoFzIdVYZo16zpAGtiHq8Xq9YbswDVR1M="; Address expectedAddress = LegacyAddress.fromBase58("1C6SjmutxV21sPdqQAWLJbvznfyCoU2zWc", MAINNET); ECKey key = ECKey.signedMessageToKey(message, sigBase64); Address gotAddress = key.toAddress(ScriptType.P2PKH, MAINNET); assertEquals(expectedAddress, gotAddress); } @Test public void verifyMessageSignedWithNativeSegwitP2WPKHAddress() throws Exception { String message = "This msg was signed with a native SegWit v0 address, the signature header byte therefore is in the range 39-42 (according to BIP 137)."; String sigBase64 = "KH4/rrraZsPwuuW6pSKVnZVdZXmzLPBOPSS9zz6QLZnTGhO2mHFAs53QLPp94Hahz7kTgNiO6VYZpehMbNHIvNA="; Address expectedAddress = SegwitAddress.fromBech32("bc1qvcl0z7f25sf2u8up5wplk7arwclghh7de8fy6l", MAINNET); ECKey key = ECKey.signedMessageToKey(message, sigBase64); Address gotAddress = key.toAddress(ScriptType.P2WPKH, MAINNET); assertEquals(expectedAddress, gotAddress); } @Test public void verifyMessageSignedLegacySegwitP2SH_P2WPKHAddress() throws Exception { String message = "This message was signed with a P2SH-P2WPKH address, the signature header byte therefore is in the range 35-38 (according to BIP 137)."; String sigBase64 = "I6CwPW9ErVV8SphnQbHnOfYcwcqMdJaZRkym5QHzykpzVw38SrftZFaWoqMl+pvJ92hOyj8PjDOQOT2hDXtk5V0="; Address expectedAddress = LegacyAddress.fromBase58("3HnHC8dJCqixUBFNYXdz2LFXQwvAkkTR3m", MAINNET); ECKey key = ECKey.signedMessageToKey(message, sigBase64); final byte[] segwitV0_OpPush20 = {0x00, 0x14}; byte[] segwitV0ScriptPubKey = Bytes.concat(segwitV0_OpPush20, key.getPubKeyHash()); // as defined in BIP 141 byte[] scriptHashOfSegwitScript = CryptoUtils.sha256hash160(segwitV0ScriptPubKey); Address gotAddress = LegacyAddress.fromScriptHash(MAINNET, scriptHashOfSegwitScript); assertEquals(expectedAddress, gotAddress); } @Test public void findRecoveryId() { ECKey key = new ECKey(); String message = "Hello World!"; Sha256Hash hash = Sha256Hash.of(message.getBytes()); ECKey.ECDSASignature sig = key.sign(hash); key = ECKey.fromPublicOnly(key); List<Byte> possibleRecIds = Lists.newArrayList((byte) 0, (byte) 1, (byte) 2, (byte) 3); byte recId = key.findRecoveryId(hash, sig); assertTrue(possibleRecIds.contains(recId)); } @Test public void keyRecoveryTestVector() { // a test that exercises key recovery with findRecoveryId() on a test vector // test vector from https://crypto.stackexchange.com/a/41339 ECKey key = ECKey.fromPrivate( new BigInteger("ebb2c082fd7727890a28ac82f6bdf97bad8de9f5d7c9028692de1a255cad3e0f", 16)); String message = "Maarten Bodewes generated this test vector on 2016-11-08"; Sha256Hash hash = Sha256Hash.of(message.getBytes()); ECKey.ECDSASignature sig = key.sign(hash); key = ECKey.fromPublicOnly(key); byte recId = key.findRecoveryId(hash, sig); byte expectedRecId = 0; assertEquals(recId, expectedRecId); ECKey pubKey = ECKey.fromPublicOnly(key); ECKey recoveredKey = ECKey.recoverFromSignature(recId, sig, hash, true); assertEquals(recoveredKey, pubKey); } @Test public void keyRecoveryWithFindRecoveryId() { ECKey key = new ECKey(); String message = "Hello World!"; Sha256Hash hash = Sha256Hash.of(message.getBytes()); ECKey.ECDSASignature sig = key.sign(hash); byte recId = key.findRecoveryId(hash, sig); ECKey pubKey = ECKey.fromPublicOnly(key); ECKey recoveredKey = ECKey.recoverFromSignature(recId, sig, hash, true); assertEquals(recoveredKey, pubKey); } @Test public void keyRecovery() { ECKey key = new ECKey(); String message = "Hello World!"; Sha256Hash hash = Sha256Hash.of(message.getBytes()); ECKey.ECDSASignature sig = key.sign(hash); key = ECKey.fromPublicOnly(key); boolean found = false; for (int i = 0; i < 4; i++) { ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true); Objects.requireNonNull(key2); if (key.equals(key2)) { found = true; break; } } assertTrue(found); } @Test public void testUnencryptedCreate() { TimeUtils.setMockClock(); ECKey key = new ECKey(); Optional<Instant> time = key.creationTime(); assertTrue(time.isPresent()); assertFalse(key.isEncrypted()); byte[] originalPrivateKeyBytes = key.getPrivKeyBytes(); ECKey encryptedKey = key.encrypt(keyCrypter, keyCrypter.deriveKey(PASSWORD1)); assertEquals(time, encryptedKey.creationTime()); assertTrue(encryptedKey.isEncrypted()); assertNull(encryptedKey.getSecretBytes()); key = encryptedKey.decrypt(keyCrypter.deriveKey(PASSWORD1)); assertFalse(key.isEncrypted()); assertArrayEquals(originalPrivateKeyBytes, key.getPrivKeyBytes()); } @Test public void testEncryptedCreate() { ECKey unencryptedKey = new ECKey(); byte[] originalPrivateKeyBytes = Objects.requireNonNull(unencryptedKey.getPrivKeyBytes()); log.info("Original private key = " + ByteUtils.formatHex(originalPrivateKeyBytes)); EncryptedData encryptedPrivateKey = keyCrypter.encrypt(unencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1)); ECKey encryptedKey = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, unencryptedKey.getPubKey()); assertTrue(encryptedKey.isEncrypted()); assertNull(encryptedKey.getSecretBytes()); ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter.deriveKey(PASSWORD1)); assertFalse(rebornUnencryptedKey.isEncrypted()); assertArrayEquals(originalPrivateKeyBytes, rebornUnencryptedKey.getPrivKeyBytes()); } @Test public void testEncryptionIsReversible() { ECKey originalUnencryptedKey = new ECKey(); EncryptedData encryptedPrivateKey = keyCrypter.encrypt(originalUnencryptedKey.getPrivKeyBytes(), keyCrypter.deriveKey(PASSWORD1)); ECKey encryptedKey = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, originalUnencryptedKey.getPubKey()); // The key should be encrypted assertTrue("Key not encrypted at start", encryptedKey.isEncrypted()); // Check that the key can be successfully decrypted back to the original. assertTrue("Key encryption is not reversible but it should be", ECKey.encryptionIsReversible(originalUnencryptedKey, encryptedKey, keyCrypter, keyCrypter.deriveKey(PASSWORD1))); // Check that key encryption is not reversible if a password other than the original is used to generate the AES key. assertFalse("Key encryption is reversible with wrong password", ECKey.encryptionIsReversible(originalUnencryptedKey, encryptedKey, keyCrypter, keyCrypter.deriveKey(WRONG_PASSWORD))); // Change one of the encrypted key bytes (this is to simulate a faulty keyCrypter). // Encryption should not be reversible byte[] goodEncryptedPrivateKeyBytes = encryptedPrivateKey.encryptedBytes; // Break the encrypted private key and check it is broken. byte[] badEncryptedPrivateKeyBytes = new byte[goodEncryptedPrivateKeyBytes.length]; encryptedPrivateKey = new EncryptedData(encryptedPrivateKey.initialisationVector, badEncryptedPrivateKeyBytes); ECKey badEncryptedKey = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, originalUnencryptedKey.getPubKey()); assertFalse("Key encryption is reversible with faulty encrypted bytes", ECKey.encryptionIsReversible(originalUnencryptedKey, badEncryptedKey, keyCrypter, keyCrypter.deriveKey(PASSWORD1))); } @Test public void testToString() { ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); // An example private key. assertEquals("ECKey{pub HEX=04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7, isEncrypted=false, isPubKeyOnly=false}", key.toString()); assertEquals("ECKey{pub HEX=04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7, priv HEX=000000000000000000000000000000000000000000000000000000000000000a, priv WIF=5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreBoNWTw6, isEncrypted=false, isPubKeyOnly=false}", key.toStringWithPrivate(null, MAINNET)); } @Test public void testGetPrivateKeyAsHex() { ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); // An example private key. assertEquals("000000000000000000000000000000000000000000000000000000000000000a", key.getPrivateKeyAsHex()); } @Test public void testGetPublicKeyAsHex() { ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); // An example private key. assertEquals("04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.getPublicKeyAsHex()); } @Test public void keyRecoveryWithEncryptedKey() { ECKey unencryptedKey = new ECKey(); AesKey aesKey = keyCrypter.deriveKey(PASSWORD1); ECKey encryptedKey = unencryptedKey.encrypt(keyCrypter, aesKey); String message = "Goodbye Jupiter!"; Sha256Hash hash = Sha256Hash.of(message.getBytes()); ECKey.ECDSASignature sig = encryptedKey.sign(hash, aesKey); unencryptedKey = ECKey.fromPublicOnly(unencryptedKey); boolean found = false; for (int i = 0; i < 4; i++) { ECKey key2 = ECKey.recoverFromSignature(i, sig, hash, true); Objects.requireNonNull(key2); if (unencryptedKey.equals(key2)) { found = true; break; } } assertTrue(found); } @Test public void roundTripDumpedPrivKey() { ECKey key = new ECKey(); assertTrue(key.isCompressed()); String base58 = key.getPrivateKeyEncoded(TESTNET).toString(); ECKey key2 = DumpedPrivateKey.fromBase58(TESTNET, base58).getKey(); assertTrue(key2.isCompressed()); assertArrayEquals(key.getPrivKeyBytes(), key2.getPrivKeyBytes()); assertArrayEquals(key.getPubKey(), key2.getPubKey()); } @Test public void clear() { ECKey unencryptedKey = new ECKey(); ECKey encryptedKey = (new ECKey()).encrypt(keyCrypter, keyCrypter.deriveKey(PASSWORD1)); checkSomeBytesAreNonZero(unencryptedKey.getPrivKeyBytes()); // The encryptedPrivateKey should be null in an unencrypted ECKey anyhow but check all the same. assertTrue(unencryptedKey.getEncryptedPrivateKey() == null); checkSomeBytesAreNonZero(encryptedKey.getSecretBytes()); checkSomeBytesAreNonZero(encryptedKey.getEncryptedPrivateKey().encryptedBytes); checkSomeBytesAreNonZero(encryptedKey.getEncryptedPrivateKey().initialisationVector); } @Test public void testCanonicalSigs() throws Exception { // Tests the canonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_canonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.available() > 0) { while (in.available() > 0 && in.read() != '"') ; if (in.available() < 1) break; StringBuilder sig = new StringBuilder(); int c; while (in.available() > 0 && (c = in.read()) != '"') sig.append((char)c); assertTrue(TransactionSignature.isEncodingCanonical(ByteUtils.parseHex(sig.toString()))); } in.close(); } @Test public void testNonCanonicalSigs() throws Exception { // Tests the noncanonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_noncanonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.available() > 0) { while (in.available() > 0 && in.read() != '"') ; if (in.available() < 1) break; StringBuilder sig = new StringBuilder(); int c; while (in.available() > 0 && (c = in.read()) != '"') sig.append((char)c); try { final String sigStr = sig.toString(); assertFalse(TransactionSignature.isEncodingCanonical(ByteUtils.parseHex(sigStr))); } catch (IllegalArgumentException e) { // Expected for non-hex strings in the JSON that we should ignore } } in.close(); } @Test public void testCreatedSigAndPubkeyAreCanonical() { // Tests that we will not generate non-canonical pubkeys or signatures // We dump failed data to error log because this test is not expected to be deterministic ECKey key = new ECKey(); if (!ECKey.isPubKeyCanonical(key.getPubKey())) { log.error(ByteUtils.formatHex(key.getPubKey())); fail(); } byte[] hash = new byte[32]; new Random().nextBytes(hash); byte[] sigBytes = key.sign(Sha256Hash.wrap(hash)).encodeToDER(); byte[] encodedSig = Arrays.copyOf(sigBytes, sigBytes.length + 1); encodedSig[sigBytes.length] = Transaction.SigHash.ALL.byteValue(); if (!TransactionSignature.isEncodingCanonical(encodedSig)) { log.error(ByteUtils.formatHex(sigBytes)); fail(); } } @Test public void isPubKeyCompressed() { assertFalse(ECKey.isPubKeyCompressed(ByteUtils.parseHex( "04cfb4113b3387637131ebec76871fd2760fc430dd16de0110f0eb07bb31ffac85e2607c189cb8582ea1ccaeb64ffd655409106589778f3000fdfe3263440b0350"))); assertTrue(ECKey.isPubKeyCompressed(ByteUtils.parseHex( "036d27f617ce7b0cbdce0abebd1c7aafc147bd406276e6a08d64d7a7ed0ca68f0e"))); assertTrue(ECKey.isPubKeyCompressed(ByteUtils.parseHex( "0238746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f"))); } @Test(expected = IllegalArgumentException.class) public void isPubKeyCompressed_tooShort() { ECKey.isPubKeyCompressed(ByteUtils.parseHex("036d")); } @Test(expected = IllegalArgumentException.class) public void isPubKeyCompressed_illegalSign() { ECKey.isPubKeyCompressed(ByteUtils.parseHex("0438746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f")); } private static boolean checkSomeBytesAreNonZero(byte[] bytes) { if (bytes == null) return false; for (byte b : bytes) if (b != 0) return true; return false; } @Test public void testPublicKeysAreEqual() { ECKey key = new ECKey(); ECKey pubKey1 = ECKey.fromPublicOnly(key); assertTrue(pubKey1.isCompressed()); ECKey pubKey2 = pubKey1.decompress(); assertEquals(pubKey1, pubKey2); assertEquals(pubKey1.hashCode(), pubKey2.hashCode()); } @Test(expected = IllegalArgumentException.class) public void fromPrivate_exceedsSize() { final byte[] bytes = new byte[33]; bytes[0] = 42; ECKey.fromPrivate(bytes); } }
29,602
46.82391
578
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/MnemonicCodeVectorsTest.java
/* * Copyright 2013 Ken Sedgwick * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.bitcoinj.base.internal.ByteUtils; import static org.bitcoinj.base.internal.InternalUtils.SPACE_JOINER; import static org.bitcoinj.base.internal.InternalUtils.WHITESPACE_SPLITTER; import static org.junit.Assert.assertEquals; /** * This is a parametrized test class to execute all {@link MnemonicCode} test vectors. */ @RunWith(value = Parameterized.class) public class MnemonicCodeVectorsTest { private MnemonicCode mc; private String vectorEntropy; private String vectorMnemonicCode; private String vectorSeed; private String vectorPassphrase; public MnemonicCodeVectorsTest(String vectorEntropy, String vectorMnemonicCode, String vectorSeed, String vectorPassphrase) { this.vectorEntropy = vectorEntropy; this.vectorMnemonicCode = vectorMnemonicCode; this.vectorSeed = vectorSeed; this.vectorPassphrase = vectorPassphrase; } @Before public void setup() throws IOException { mc = new MnemonicCode(); } @Test public void testMnemonicCode() throws Exception { final List<String> mnemonicCode = mc.toMnemonic(ByteUtils.parseHex(vectorEntropy)); final byte[] seed = MnemonicCode.toSeed(mnemonicCode, vectorPassphrase); final byte[] entropy = mc.toEntropy(WHITESPACE_SPLITTER.splitToList(vectorMnemonicCode)); assertEquals(vectorEntropy, ByteUtils.formatHex(entropy)); assertEquals(vectorMnemonicCode, SPACE_JOINER.join(mnemonicCode)); assertEquals(vectorSeed, ByteUtils.formatHex(seed)); } /** * This method defines and supplies the parameters (test vectors) to be used in the testing of {@link MnemonicCode}. * @return A list of groups of test vectors */ @Parameterized.Parameters(name = "Vector set {index} (entropy={0}, passphrase={3})") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ /* * The following vectors are from https://github.com/trezor/python-mnemonic/blob/master/vectors.json */ { "00000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04", "TREZOR" }, { "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank yellow", "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607", "TREZOR" }, { "80808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8", "TREZOR" }, { "ffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069", "TREZOR" }, { "000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent", "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa", "TREZOR" }, { "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will", "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd", "TREZOR" }, { "808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always", "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65", "TREZOR" }, { "ffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when", "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528", "TREZOR" }, { "0000000000000000000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8", "TREZOR" }, { "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87", "TREZOR" }, { "8080808080808080808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f", "TREZOR" }, { "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad", "TREZOR" }, { "9e885d952ad362caeb4efe34a8e91bd2", "ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic", "274ddc525802f7c828d8ef7ddbcdc5304e87ac3535913611fbbfa986d0c9e5476c91689f9c8a54fd55bd38606aa6a8595ad213d4c9c9f9aca3fb217069a41028", "TREZOR" }, { "6610b25967cdcca9d59875f5cb50b0ea75433311869e930b", "gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog", "628c3827a8823298ee685db84f55caa34b5cc195a778e52d45f59bcf75aba68e4d7590e101dc414bc1bbd5737666fbbef35d1f1903953b66624f910feef245ac", "TREZOR" }, { "68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c", "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length", "64c87cde7e12ecf6704ab95bb1408bef047c22db4cc7491c4271d170a1b213d20b385bc1588d9c7b38f1b39d415665b8a9030c9ec653d75e65f847d8fc1fc440", "TREZOR" }, { "c0ba5a8e914111210f2bd131f3d5e08d", "scheme spot photo card baby mountain device kick cradle pact join borrow", "ea725895aaae8d4c1cf682c1bfd2d358d52ed9f0f0591131b559e2724bb234fca05aa9c02c57407e04ee9dc3b454aa63fbff483a8b11de949624b9f1831a9612", "TREZOR" }, { "6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3", "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave", "fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b10b5382772db8796e52837b54468aeb312cfc3d", "TREZOR" }, { "9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863", "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside", "72be8e052fc4919d2adf28d5306b5474b0069df35b02303de8c1729c9538dbb6fc2d731d5f832193cd9fb6aeecbc469594a70e3dd50811b5067f3b88b28c3e8d", "TREZOR" }, { "23db8160a31d3e0dca3688ed941adbf3", "cat swing flag economy stadium alone churn speed unique patch report train", "deb5f45449e615feff5640f2e49f933ff51895de3b4381832b3139941c57b59205a42480c52175b6efcffaa58a2503887c1e8b363a707256bdd2b587b46541f5", "TREZOR" }, { "8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0", "light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access", "4cbdff1ca2db800fd61cae72a57475fdc6bab03e441fd63f96dabd1f183ef5b782925f00105f318309a7e9c3ea6967c7801e46c8a58082674c860a37b93eda02", "TREZOR" }, { "066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad", "all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform", "26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d", "TREZOR" }, { "f30f8c1da665478f49b001d94c5fc452", "vessel ladder alter error federal sibling chat ability sun glass valve picture", "2aaa9242daafcee6aa9d7269f17d4efe271e1b9a529178d7dc139cd18747090bf9d60295d0ce74309a78852a9caadf0af48aae1c6253839624076224374bc63f", "TREZOR" }, { "c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05", "scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump", "7b4a10be9d98e6cba265566db7f136718e1398c71cb581e1b2f464cac1ceedf4f3e274dc270003c670ad8d02c4558b2f8e39edea2775c9e232c7cb798b069e88", "TREZOR" }, { "f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold", "01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998", "TREZOR" }, /* * The following vectors were created to test the absence of a passphrase, * and were determined using the reference implementation at https://github.com/trezor/python-mnemonic. */ { "00000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4", "" }, { "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank yellow", "878386efb78845b3355bd15ea4d39ef97d179cb712b77d5c12b6be415fffeffe5f377ba02bf3f8544ab800b955e51fbff09828f682052a20faa6addbbddfb096", "" }, { "80808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", "77d6be9708c8218738934f84bbbb78a2e048ca007746cb764f0673e4b1812d176bbb173e1a291f31cf633f1d0bad7d3cf071c30e98cd0688b5bcce65ecaceb36", "" }, { "ffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", "b6a6d8921942dd9806607ebc2750416b289adea669198769f2e15ed926c3aa92bf88ece232317b4ea463e84b0fcd3b53577812ee449ccc448eb45e6f544e25b6", "" }, { "f30f8c1da665478f49b001d94c5fc452", "vessel ladder alter error federal sibling chat ability sun glass valve picture", "e2d7f9a462875c1325f44f321392edc8eaafebf1547c89d72d10b41b4ee23af3fb0ab010f39f5cbea3b3aa671161b58262b6a508bcbe2d34ee272a942534d45f", "" }, { "c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05", "scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump", "a555426999448df9022c3afc2ed0e4aebff3a0ac37d8a395f81412e14994efc960ed168d39a80478e0467a3d5cfc134fef2767c1d3a27f18e3afeb11bfc8e6ad", "" }, { "f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold", "b873212f885ccffbf4692afcb84bc2e55886de2dfa07d90f5c3c239abc31c0a6ce047e30fd8bf6a281e71389aa82d73df74c7bbfb3b06b4639a5cee775cccd3c", "" } }); } }
16,245
65.581967
214
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/crypto/utils/MessageVerifyUtilsTest.java
package org.bitcoinj.crypto.utils; import org.bitcoinj.base.AddressParser; import org.bitcoinj.base.DefaultAddressParser; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.fail; @RunWith(Parameterized.class) public class MessageVerifyUtilsTest { @Parameterized.Parameters public static Collection<TestVector> testVectors() { return Arrays.asList( // testvectors from ECKeyTest.java: new TestVector(MainNetParams.get(), "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag", "hello", "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8=", true, "P2PKH address from compressed public key"), new TestVector(MainNetParams.get(), "1C6SjmutxV21sPdqQAWLJbvznfyCoU2zWc", "message signed using an p2pkh address derived from an uncompressed public key", "HDoME2gqLJApQTOLnce4J7BZcO1yIxUSP6tdKIUBLO99E+BH3uABshRoFzIdVYZo16zpAGtiHq8Xq9YbswDVR1M=", true, "P2PKH address from uncompressed public key"), new TestVector(MainNetParams.get(), "bc1qvcl0z7f25sf2u8up5wplk7arwclghh7de8fy6l", "This msg was signed with a native SegWit v0 address, the signature header byte therefore is in the range 39-42 (according to BIP 137).", "KH4/rrraZsPwuuW6pSKVnZVdZXmzLPBOPSS9zz6QLZnTGhO2mHFAs53QLPp94Hahz7kTgNiO6VYZpehMbNHIvNA=", true, "signature from native Segwit (bech32) address"), new TestVector(MainNetParams.get(), "3HnHC8dJCqixUBFNYXdz2LFXQwvAkkTR3m", "This message was signed with a P2SH-P2WPKH address, the signature header byte therefore is in the range 35-38 (according to BIP 137).", "I6CwPW9ErVV8SphnQbHnOfYcwcqMdJaZRkym5QHzykpzVw38SrftZFaWoqMl+pvJ92hOyj8PjDOQOT2hDXtk5V0=", true, "signature from a P2WPKH-wrapped-into-P2SH type address"), // collection of testvectors found in other projects or online new TestVector(MainNetParams.get(), "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", "vires is numeris", "G8JawPtQOrybrSP1WHQnQPr67B9S3qrxBrl1mlzoTJOSHEpmnF7D3+t+LX0Xei9J20B5AIdPbeL3AaTBZ4N3bY0=", true, "uncompressed public key"), new TestVector(MainNetParams.get(), "1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs", "vires is numeris", "H8JawPtQOrybrSP1WHQnQPr67B9S3qrxBrl1mlzoTJOSHEpmnF7D3+t+LX0Xei9J20B5AIdPbeL3AaTBZ4N3bY0=", true, "compressed public key"), new TestVector(MainNetParams.get(), "3JvL6Ymt8MVWiCNHC7oWU6nLeHNJKLZGLN", "vires is numeris", "JF8nHqFr3K2UKYahhX3soVeoW8W1ECNbr0wfck7lzyXjCS5Q16Ek45zyBuy1Fiy9sTPKVgsqqOuPvbycuVSSVl8=", true, "legacy segwit (always compressed pubkey)"), new TestVector(MainNetParams.get(), "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", "vires is numeris", "KF8nHqFr3K2UKYahhX3soVeoW8W1ECNbr0wfck7lzyXjCS5Q16Ek45zyBuy1Fiy9sTPKVgsqqOuPvbycuVSSVl8=", true, "segwit (always compressed pubkey)"), new TestVector(MainNetParams.get(), "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", "foobar", "G8JawPtQOrybrSP1WHQnQPr67B9S3qrxBrl1mlzoTJOSHEpmnF7D3+t+LX0Xei9J20B5AIdPbeL3AaTBZ4N3bY0=", false, "fail for the wrong message"), new TestVector(MainNetParams.get(), "1111111111111111111114oLvT2", "vires is numeris", "H8JawPtQOrybrSP1WHQnQPr67B9S3qrxBrl1mlzoTJOSHEpmnF7D3+t+LX0Xei9J20B5AIdPbeL3AaTBZ4N3bY0=", false, "fail for the wrong address"), new TestVector(MainNetParams.get(), "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", "vires is numeris", "H8JawPtQOrybrSP1WHQnQPr67B9S3qrxBrl1mlzoTJOSHEpmnF7D3+t+LX0Xei9J20B5AIdPbeL3AaTBZ4N3bY0=", false, "should fail because -> uncompressed address,but compressed flag in signature"), new TestVector(MainNetParams.get(), "1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs", "vires is numeris", "G8JawPtQOrybrSP1WHQnQPr67B9S3qrxBrl1mlzoTJOSHEpmnF7D3+t+LX0Xei9J20B5AIdPbeL3AaTBZ4N3bY0=", false, "should fail because -> compressed address,but uncompressed flag in signature"), new TestVector(MainNetParams.get(), "bc1q6nmtgxgfx2up7zuuydglme8fydugkh7jsrnz7f", "12345678", "J4cRzK+gDAJfGddCKB9EAHA2rOnxCZXowwGO/Zu4AmMvONsAE0b8vTez6pvMYl+gTjyn9AJv7PieFrGVTSWKK4M=", true, "shouldValidate_P2WPKH"), new TestVector(MainNetParams.get(), "bc1qp2ltq2tgsjav3rq3lt38lzfnpzewv8fcharjyk", "1113875075", "HzXKbcRCe5By+a/7CRh0QMd6B2SdnDKcNKzieBRCkYtzCrBquTRZO49iDmwWqiAMphlpqmVQUxmHLSe0Y9GGysQ=", true, "shouldValidate_P2WPKH_GeneratedByElectrum"), new TestVector(MainNetParams.get(), "33wW4GTkzMhgS3QvTP5K7jKY7i8zuzwqKg", "12345678", "I6N4ZR5jYHLO9HgpGjlWF87TU91cRELtg84TZmEJQnkGQ9XGNQiGd2MB+XKkbzPVpgbvqrgvbVV+n81X1m52TYI=", true, "shouldValidate P2SH-P2WPKH"), new TestVector(MainNetParams.get(), "1EqTxusZzKmMhHhCevCmh7fWMVf8PuD6TT", "12345678", "HxeBIxrx4VFWCEqMEiTlK/PVjqYBrkgty1ileKE3bteSPUDIGJOMOvjhyG/+WRAgT+mTEWtWpUaFmFktoKuXGmA=", true, "shouldValidate-P2PKH"), new TestVector(MainNetParams.get(), "14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e", "VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!", "IF/3lcKa73U4+LO9suit0NByKtYwoUC2rv1QSlqJXL2GfLsAmBr8UO3QOYIR6NfDBLuO+kYRgbwK+mfqSnIKie0=", true, "testcase from trezor"), new TestVector(MainNetParams.get(), "1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T", "This is an example of a signed message.", "G6d+Aanhe6FYuWLP718T3+1nb/wrS62iTlj3hEWLUrl0IUcNAB1T1YgM9eEOdvAr4+gL8h4YOYy9QejDtK90yMI=", true, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T", "This is an example of a signed message.", "G6d+Aanhe6FYuWLP718T3+1nb/wrS62iTlj3hEWLUrl0IUcNAB1T1YgM9eEOdvAr4+gL8h4YOYy9QejDtK90yAA=", false, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T", "This is an example of a signed message!", "G6d+Aanhe6FYuWLP718T3+1nb/wrS62iTlj3hEWLUrl0IUcNAB1T1YgM9eEOdvAr4+gL8h4YOYy9QejDtK90yMI=", false, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8", "This is an example of a signed message.", "H0Tj5GH3yp9XxHLOGighTfHeHa3vtlUaMtGQe4DHTVofv9baq6Et2MsGaZzj9pQfvg85V7WALRMHYYEEbnQeqq8=", true, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8", "This is an example of a signed message.", "H0Tj5GH3yp9XxHLOGighTfHeHa3vtlUaMtGQe4DHTVofv9baq6Et2MsGaZzj9pQfvg85V7WALRMHYYEEbnQeqgA=", false, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8", "This is an example of a signed message!", "H0Tj5GH3yp9XxHLOGighTfHeHa3vtlUaMtGQe4DHTVofv9baq6Et2MsGaZzj9pQfvg85V7WALRMHYYEEbnQeqq8=", false, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e", "This is an example of a signed message.", "IJ4j7fDk5H/x3sJ/Ms14xQ507wGO6Kat81rhfHqbDdlvSLST/X26sD77b0OcY4PJUjs7vF8afRWKavkKsVTpvoA=", true, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e", "This is an example of a signed message.", "IJ4j7fDk5H/x3sJ/Ms14xQ507wGO6Kat81rhfHqbDdlvSLST/X26sD77b0OcY4PJUjs7vF8afRWKavkKsVTpvgA=", false, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e", "This is an example of a signed message!", "IJ4j7fDk5H/x3sJ/Ms14xQ507wGO6Kat81rhfHqbDdlvSLST/X26sD77b0OcY4PJUjs7vF8afRWKavkKsVTpvoA=", false, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "1KzXE97kV7DrpxCViCN3HbGbiKhzzPM7TQ", "žluťoučký kůň úpěl ďábelské ódy", "HMaU8PI5Ad/jYDeJFC82o/xYLQ1cDschXPLM1kHk43IoUE89TcPuoou9v12ifEnUY1wJcATZ8ih1DM2Dao4UYMA=", true, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1", "This is an example of a signed message.", "JJ4j7fDk5H/x3sJ/Ms14xQ507wGO6Kat81rhfHqbDdlvSLST/X26sD77b0OcY4PJUjs7vF8afRWKavkKsVTpvoA=", true, "test vector from bitcoinjs-message"), new TestVector(MainNetParams.get(), "3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1", "VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!", "JF/3lcKa73U4+LO9suit0NByKtYwoUC2rv1QSlqJXL2GfLsAmBr8UO3QOYIR6NfDBLuO+kYRgbwK+mfqSnIKie0=", true, "test case from trezor"), new TestVector(MainNetParams.get(), "3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1", "Příšerně žluťoučký kůň úpěl ďábelské ódy zákeřný učeň běží podél zóny úlů", "JNDsAu2NqN8j5/6eaA54Z8wpAxL+HJcHSdgwbdrRoe2kHGp3GxPUld0iWxOwqdD5FamE7j0HA/kih7+ACfu599Y=", true, ""), new TestVector(MainNetParams.get(), "bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j", "This is an example of a signed message.", "KJ4j7fDk5H/x3sJ/Ms14xQ507wGO6Kat81rhfHqbDdlvSLST/X26sD77b0OcY4PJUjs7vF8afRWKavkKsVTpvoA=", true, ""), new TestVector(MainNetParams.get(), "bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j", "VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!VeryLongMessage!", "KF/3lcKa73U4+LO9suit0NByKtYwoUC2rv1QSlqJXL2GfLsAmBr8UO3QOYIR6NfDBLuO+kYRgbwK+mfqSnIKie0=", true, "test case from trezor"), new TestVector(MainNetParams.get(), "bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j", "Příšerně žluťoučký kůň úpěl ďábelské ódy zákeřný učeň běží podél zóny úlů", "KNDsAu2NqN8j5/6eaA54Z8wpAxL+HJcHSdgwbdrRoe2kHGp3GxPUld0iWxOwqdD5FamE7j0HA/kih7+ACfu599Y=", true, "test case from trezor"), new TestVector(MainNetParams.get(), "bc1qr98j5exfpgn3g6tup064sjtr8hqf4hwesg8x2n", "⚡️⚡️⚡️ We löööve Lightning. This signature was created with Electrum 4.2.1 and a P2PWKH address (native segwit).", "ICD+yhkWDgBMHLhLwFkKC7ndcc2STRSCWApKDQDBhuuCd9AjigggCMGyrZvXNWBXn650WB9uncaq22adCyYYNQQ=", true, "Native Segwit generated with Electrum 4.2.1"), new TestVector(MainNetParams.get(), "19rK6PL7KUQNk2Z9dGRGjnhDd6QUA5QXwa", "⚡️⚡️⚡️🤯🥳🥸 We still lööve Lightning. :) This signature was created with Electrum 4.2.1 and a compressed P2PKH address (legacy 1.. address).", "HyKVgA7lPUXt50BqMhRYrLQNiP3hVOiU9SavIzopactCUWcy9NVcIb/FvmknKQQpeH3A38DZv7mHM/uSQPXhWf8=", true, "Compressed P2PKH (legacy address) sig generated with Electrum 4.2.1"), new TestVector(MainNetParams.get(), "1FizteKkFBDvqYX5FKSqaXXsoieFv8YXC3", "😶‍🌫️🧐🤓 Old and legäcy, this signature was created with Electrum 4.2.1 and a UNCOMPRESSED P2PKH address (1er.. address). Uncompressed is soooo retro... 🙈", "HBLk5Jy5WzCGBpzrNQxABbJ4lT34f12uwMgmg4TSwIAXWQZ2FvLXHib1Vl9n9TmFWIdwGiHuNtpv+q0a7sHOT5U=", true, "Uncompressed P2PKH (legacy address) sig generated with Electrum 4.2.1"), new TestVector(MainNetParams.get(), "383jWSXohdSkpLKQPV2a91xqqJ83ZkGrA4", "🥸🤮😻 Legäcy segwit, wrapped into P2SH, compressed, this signature was created with Electrum 4.2.1 P2SH-P2WPKH address (3er.. legacy segwit address).", "H3B3EvJKTvVSjr8o7ZssUfeoEfauqj3jRIs0Js/QCsQjN230pIM2C3GMqmDDP+Uo+OB6OZaXiVrAkuSmJ0iABvU=", true, "Uncompressed P2PKH (legacy address) sig generated with Electrum 4.2.1"), new TestVector(MainNetParams.get(), "bc1qzeacswvlulg0jngad9gmtkvdp9lwum42wwzdu5", "Hello", "HxuuWQwjw0417fLV9L0kWbt7w9XOIWKhHMhjXhyXTczcSozGTXM4knqdISiYbbmqSRXqI5mNTWH9qkDoqZTpnPc=", true, "example from COLDCARD: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-July/020762.html"), new TestVector(MainNetParams.get(), "14YPSNPi6NSXnUxtPAsyJSuw3pv7AU3Cag", "hello", "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8=", true, "Testvector from bitcoinJ"), new TestVector(MainNetParams.get(), "17o6NDP6nemtm8ZundHEMbxmHsPGnVyggs", "聡中本", "H4c/RMMLsKJvxDk7uI2vt6qSbzyfvKGo+g8uNOsEhIKxWgzqZk547uI22fg5MX+jI17yvkB5qyizrO6DUJ/HfYw=", true, "another Testvector from bitcoinJ"), new TestVector(MainNetParams.get(), "1FbPLPR1XoufBQRPGd9JBLPbKLaGjbax5m", "Craig Steven Wright is a liar and a fraud. He doesn't have the keys used to sign this message.\n\nThe Lightning Network is a significant achievement. However, we need to continue work on improving on-chain capacity.\n\nUnfortunately, the solution is not to just change a constant in the code or to allow powerful participants to force out others.\n\nWe are all Satoshi", "G3SsgKMKAOiOaMzKSGqpKo5MFpt0biP9MbO5UkSl7VxRKcv6Uz+3mHsuEJn58lZlRksvazOKAtuMUMolg/hE9WI=", true, "publicly available signature from here: https://archive.ph/Z1oB8"), new TestVector(TestNet3Params.get(), "mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL", "This is an example of a signed message.", "IJ4j7fDk5H/x3sJ/Ms14xQ507wGO6Kat81rhfHqbDdlvSLST/X26sD77b0OcY4PJUjs7vF8afRWKavkKsVTpvoA=", true, "Testnet test vector from Trezor repo") ); } private final TestVector testVector; public MessageVerifyUtilsTest(TestVector testVector) { this.testVector = testVector; } @Test public void testMessageSignatureVerification() { final AddressParser addressParser = new DefaultAddressParser(); try { MessageVerifyUtils.verifyMessage( addressParser.parseAddress(testVector.address, testVector.networkParameters.network()), testVector.message, testVector.signature ); if (!testVector.shouldVerify) { fail("verification should have failed, but succeed: " + testVector + "\n"); } } catch (Exception e) { if (testVector.shouldVerify) { fail("verification should have succeeded, but failed: " + testVector + "\n"); } } } private static class TestVector { private final NetworkParameters networkParameters; private final String address; private final String message; private final String signature; private final boolean shouldVerify; private final String comment; public TestVector(NetworkParameters network, String address, String message, String signature, boolean shouldVerify, String comment) { this.networkParameters = network; this.address = address; this.message = message; this.signature = signature; this.shouldVerify = shouldVerify; this.comment = comment; } @Override public String toString() { return "TestVector{" + "address='" + address + '\'' + ", message='" + message + '\'' + ", signature='" + signature + '\'' + ", shouldVerify=" + shouldVerify + ", comment='" + comment + '\'' + '}'; } } }
17,831
142.806452
1,249
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/MessageTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.junit.Test; public class MessageTest { @Test public void deprecatedMembers() { Message message = new UnknownMessage("dummy"); message.bitcoinSerialize(); message.unsafeBitcoinSerialize(); message.getMessageSize(); } }
915
29.533333
75
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/TransactionWitnessTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.SignatureDecodeException; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @RunWith(JUnitParamsRunner.class) public class TransactionWitnessTest { @Test public void testToString() { TransactionWitness w1 = TransactionWitness.EMPTY; assertEquals("", w1.toString()); TransactionWitness w2 = TransactionWitness.of(new byte[0], new byte[0]); assertEquals("EMPTY EMPTY", w2.toString()); TransactionWitness w3 = TransactionWitness.of(ByteUtils.parseHex("123aaa"), ByteUtils.parseHex("123bbb"), new byte[0], ByteUtils.parseHex("123ccc")); assertEquals("123aaa 123bbb EMPTY 123ccc", w3.toString()); } @Test public void testRedeemP2WSH() throws SignatureDecodeException { ECKey.ECDSASignature ecdsaSignature1 = TransactionSignature.decodeFromDER(ByteUtils.parseHex("3045022100c3d84f7bf41c7eda3b23bbbccebde842a451c1a0aca39df706a3ff2fe78b1e0a02206e2e3c23559798b02302ad6fa5ddbbe87af5cc7d3b9f86b88588253770ab9f79")); TransactionSignature signature1 = new TransactionSignature(ecdsaSignature1, Transaction.SigHash.ALL, false); ECKey.ECDSASignature ecdsaSignature2 = TransactionSignature.decodeFromDER(ByteUtils.parseHex("3045022100fcfe4a58f2878047ef7c5889fc52a3816ad2dd218807daa3c3eafd4841ffac4d022073454df7e212742f0fee20416b418a2c1340a33eebed5583d19a61088b112832")); TransactionSignature signature2 = new TransactionSignature(ecdsaSignature2, Transaction.SigHash.ALL, false); Script witnessScript = Script.parse(ByteUtils.parseHex("522102bb65b325a986c5b15bd75e0d81cf149219597617a70995efedec6309b4600fa02103c54f073f5db9f68915019801435058c9232cb72c6528a2ca15af48eb74ca8b9a52ae")); TransactionWitness witness = TransactionWitness.redeemP2WSH(witnessScript, signature1, signature2); assertEquals(4, witness.getPushCount()); assertArrayEquals(new byte[]{}, witness.getPush(0)); assertArrayEquals(signature1.encodeToBitcoin(), witness.getPush(1)); assertArrayEquals(signature2.encodeToBitcoin(), witness.getPush(2)); assertArrayEquals(witnessScript.program(), witness.getPush(3)); } @Test @Parameters(method = "randomWitness") public void readAndWrite(TransactionWitness witness) { ByteBuffer buf = ByteBuffer.allocate(witness.getMessageSize()); witness.write(buf); assertFalse(buf.hasRemaining()); ((Buffer) buf).rewind(); TransactionWitness witnessCopy = TransactionWitness.read(buf); assertFalse(buf.hasRemaining()); assertEquals(witness, witnessCopy); } private Iterator<TransactionWitness> randomWitness() { Random random = new Random(); return Stream.generate(() -> { return TransactionWitness.of(Stream.generate(() -> { byte[] randomBytes = new byte[random.nextInt(50)]; random.nextBytes(randomBytes); return randomBytes; }).limit(random.nextInt(10)).collect(Collectors.toList())); }).limit(10).iterator(); } }
4,280
43.59375
248
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/BuffersTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.Buffer; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Random; import java.util.stream.Stream; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; @RunWith(JUnitParamsRunner.class) public class BuffersTest { @Test @Parameters(method = "randomBytes") public void readAndWrite(byte[] bytes) { ByteBuffer buf = ByteBuffer.allocate(VarInt.sizeOf(bytes.length) + bytes.length); Buffers.writeLengthPrefixedBytes(buf, bytes); assertFalse(buf.hasRemaining()); ((Buffer) buf).rewind(); byte[] copy = Buffers.readLengthPrefixedBytes(buf); assertFalse(buf.hasRemaining()); assertArrayEquals(bytes, copy); } private Iterator<byte[]> randomBytes() { Random random = new Random(); return Stream.generate(() -> { int length = random.nextInt(10); byte[] bytes = new byte[length]; random.nextBytes(bytes); return bytes; }).limit(10).iterator(); } // If readStr() is vulnerable this causes OutOfMemory @Test(expected = BufferUnderflowException.class) public void readStrOfExtremeLength() { VarInt length = VarInt.of(Integer.MAX_VALUE); ByteBuffer payload = ByteBuffer.wrap(length.serialize()); Buffers.readLengthPrefixedString(payload); } // If readBytes() is vulnerable this causes OutOfMemory @Test(expected = BufferUnderflowException.class) public void readByteArrayOfExtremeLength() { VarInt length = VarInt.of(Integer.MAX_VALUE); ByteBuffer payload = ByteBuffer.wrap(length.serialize()); Buffers.readLengthPrefixedBytes(payload); } }
2,626
33.565789
89
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/BitcoindComparisonTool.java
/* * Copyright 2012 Matt Corallo. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.collect.Iterables; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.net.NioClient; import org.bitcoinj.params.RegTestParams; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.FullPrunedBlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.store.MemoryFullPrunedBlockStore; import org.bitcoinj.utils.BlockFileLoader; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.InetAddress; import java.net.InetSocketAddress; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * A tool for comparing the blocks which are accepted/rejected by bitcoind/bitcoinj * It is designed to run as a testnet-in-a-box network between a single bitcoind node and bitcoinj * It is not an automated unit-test because it requires a bit more set-up...read comments below */ public class BitcoindComparisonTool { private static final Logger log = LoggerFactory.getLogger(BitcoindComparisonTool.class); private static final NetworkParameters PARAMS = RegTestParams.get(); private static FullPrunedBlockChain chain; private static Sha256Hash bitcoindChainHead; private static volatile InventoryMessage mostRecentInv = null; static class BlockWrapper { public Block block; } public static void main(String[] args) throws Exception { BriefLogFormatter.init(); System.out.println("USAGE: bitcoinjBlockStoreLocation runExpensiveTests(1/0) [port=18444]"); boolean runExpensiveTests = args.length > 1 && Integer.parseInt(args[1]) == 1; File blockFile = File.createTempFile("testBlocks", ".dat"); blockFile.deleteOnExit(); FullBlockTestGenerator generator = new FullBlockTestGenerator(PARAMS); final RuleList blockList = generator.getBlocksToTest(false, runExpensiveTests, blockFile); final Map<Sha256Hash, Block> preloadedBlocks = new HashMap<>(); final Iterator<Block> blocks = new BlockFileLoader(PARAMS.network(), Arrays.asList(blockFile)); try { FullPrunedBlockStore store = new MemoryFullPrunedBlockStore(PARAMS, blockList.maximumReorgBlockCount); //store = new MemoryFullPrunedBlockStore(params, blockList.maximumReorgBlockCount); chain = new FullPrunedBlockChain(PARAMS, store); } catch (BlockStoreException e) { e.printStackTrace(); System.exit(1); } VersionMessage ver = new VersionMessage(PARAMS, 42); ver.appendToSubVer("BlockAcceptanceComparisonTool", "1.1", null); ver.localServices = Services.of(Services.NODE_NETWORK); final Peer bitcoind = new Peer(PARAMS, ver, PeerAddress.localhost(PARAMS), new BlockChain(PARAMS, new MemoryBlockStore(PARAMS.getGenesisBlock()))); checkState(bitcoind.getVersionMessage().services().has(Services.NODE_NETWORK)); final BlockWrapper currentBlock = new BlockWrapper(); final Set<Sha256Hash> blocksRequested = Collections.synchronizedSet(new HashSet<Sha256Hash>()); final Set<Sha256Hash> blocksPendingSend = Collections.synchronizedSet(new HashSet<Sha256Hash>()); final AtomicInteger unexpectedInvs = new AtomicInteger(0); final CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); bitcoind.addConnectedEventListener(Threading.SAME_THREAD, (peer, peerCount) -> { if (!peer.getPeerVersionMessage().subVer.contains("Satoshi")) { System.out.println(); System.out.println("************************************************************************************************************************\n" + "WARNING: You appear to be using this to test an alternative implementation with full validation rules. You should go\n" + "think hard about what you're doing. Seriously, no one has gotten even close to correctly reimplementing Bitcoin\n" + "consensus rules, despite serious investment in trying. It is a huge task and the slightest difference is a huge bug.\n" + "Instead, go work on making Bitcoin Core consensus rules a shared library and use that. Seriously, you wont get it right,\n" + "and starting with this tester as a way to try to do so will simply end in pain and lost coins.\n" + "************************************************************************************************************************"); System.out.println(); } log.info("bitcoind connected"); // Make sure bitcoind has no blocks bitcoind.setDownloadParameters(false); bitcoind.startBlockChainDownload(); connectedFuture.complete(null); }); bitcoind.addDisconnectedEventListener(Threading.SAME_THREAD, (peer, peerCount) -> { log.error("bitcoind node disconnected!"); System.exit(1); }); bitcoind.addPreMessageReceivedEventListener(Threading.SAME_THREAD, (peer, m) -> { if (m instanceof HeadersMessage) { if (!((HeadersMessage) m).getBlockHeaders().isEmpty()) { Block b = Iterables.getLast(((HeadersMessage) m).getBlockHeaders()); log.info("Got header from bitcoind " + b.getHashAsString()); bitcoindChainHead = b.getHash(); } else log.info("Got empty header message from bitcoind"); return null; } else if (m instanceof Block) { log.error("bitcoind sent us a block it already had, make sure bitcoind has no blocks!"); System.exit(1); } else if (m instanceof GetDataMessage) { for (InventoryItem item : ((GetDataMessage) m).items) if (item.type == InventoryItem.Type.BLOCK) { log.info("Requested " + item.hash); if (currentBlock.block.getHash().equals(item.hash)) bitcoind.sendMessage(currentBlock.block); else { Block nextBlock = preloadedBlocks.get(item.hash); if (nextBlock != null) bitcoind.sendMessage(nextBlock); else { blocksPendingSend.add(item.hash); log.info("...which we will not provide yet"); } } blocksRequested.add(item.hash); } return null; } else if (m instanceof GetHeadersMessage) { try { if (currentBlock.block == null) { log.info("Got a request for a header before we had even begun processing blocks!"); return null; } LinkedList<Block> headers = new LinkedList<>(); Block it = blockList.hashHeaderMap.get(currentBlock.block.getHash()); while (it != null) { headers.addFirst(it); it = blockList.hashHeaderMap.get(it.getPrevBlockHash()); } LinkedList<Block> sendHeaders = new LinkedList<>(); boolean found = false; for (Sha256Hash hash : ((GetHeadersMessage) m).getLocator().getHashes()) { for (Block b : headers) { if (found) { sendHeaders.addLast(b); log.info("Sending header (" + b.getPrevBlockHash() + ") -> " + b.getHash()); if (b.getHash().equals(((GetHeadersMessage) m).getStopHash())) break; } else if (b.getHash().equals(hash)) { log.info("Found header " + b.getHashAsString()); found = true; } } if (found) break; } if (!found) sendHeaders = headers; bitcoind.sendMessage(new HeadersMessage(sendHeaders)); InventoryMessage i = new InventoryMessage(); for (Block b : sendHeaders) i.addBlock(b); bitcoind.sendMessage(i); } catch (Exception e) { throw new RuntimeException(e); } return null; } else if (m instanceof InventoryMessage) { if (mostRecentInv != null) { log.error("Got an inv when we weren't expecting one"); unexpectedInvs.incrementAndGet(); } mostRecentInv = (InventoryMessage) m; } return m; }); bitcoindChainHead = PARAMS.getGenesisBlock().getHash(); // bitcoind MUST be on localhost or we will get banned as a DoSer new NioClient(new InetSocketAddress(InetAddress.getLoopbackAddress(), args.length > 2 ? Integer.parseInt(args[2]) : PARAMS.getPort()), bitcoind, Duration.ofSeconds(1)); connectedFuture.get(); BlockLocator locator = new BlockLocator(); locator = locator.add(PARAMS.getGenesisBlock().getHash()); Sha256Hash hashTo = Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000000"); int rulesSinceFirstFail = 0; for (Rule rule : blockList.list) { if (rule instanceof FullBlockTestGenerator.BlockAndValidity) { FullBlockTestGenerator.BlockAndValidity block = (FullBlockTestGenerator.BlockAndValidity) rule; boolean threw = false; Block nextBlock = preloadedBlocks.get(((FullBlockTestGenerator.BlockAndValidity) rule).blockHash); // Often load at least one block because sometimes we have duplicates with the same hash (b56/57) for (int i = 0; i < 1 || nextBlock == null || !nextBlock.getHash().equals(block.blockHash); i++) { try { Block b = blocks.next(); Block oldBlockWithSameHash = preloadedBlocks.put(b.getHash(), b); if (oldBlockWithSameHash != null && oldBlockWithSameHash.getTransactions().size() != b.getTransactions().size()) blocksRequested.remove(b.getHash()); nextBlock = preloadedBlocks.get(block.blockHash); } catch (NoSuchElementException e) { if (nextBlock == null || !nextBlock.getHash().equals(block.blockHash)) throw e; } } currentBlock.block = nextBlock; log.info("Testing block {} {}", block.ruleName, currentBlock.block.getHash()); try { if (chain.add(nextBlock) != block.connects) { log.error("ERROR: Block didn't match connects flag on block \"" + block.ruleName + "\""); rulesSinceFirstFail++; } } catch (VerificationException e) { threw = true; if (!block.throwsException) { log.error("ERROR: Block didn't match throws flag on block \"" + block.ruleName + "\""); e.printStackTrace(); rulesSinceFirstFail++; } else if (block.connects) { log.error("ERROR: Block didn't match connects flag on block \"" + block.ruleName + "\""); e.printStackTrace(); rulesSinceFirstFail++; } } if (!threw && block.throwsException) { log.error("ERROR: Block didn't match throws flag on block \"" + block.ruleName + "\""); rulesSinceFirstFail++; } else if (!chain.getChainHead().getHeader().getHash().equals(block.hashChainTipAfterBlock)) { log.error("ERROR: New block head didn't match the correct value after block \"" + block.ruleName + "\""); rulesSinceFirstFail++; } else if (chain.getChainHead().getHeight() != block.heightAfterBlock) { log.error("ERROR: New block head didn't match the correct height after block " + block.ruleName); rulesSinceFirstFail++; } // Shouldnt double-request boolean shouldntRequest = blocksRequested.contains(nextBlock.getHash()); if (shouldntRequest) blocksRequested.remove(nextBlock.getHash()); InventoryMessage message = new InventoryMessage(); message.addBlock(nextBlock); bitcoind.sendMessage(message); log.info("Sent inv with block " + nextBlock.getHashAsString()); if (blocksPendingSend.contains(nextBlock.getHash())) { bitcoind.sendMessage(nextBlock); log.info("Sent full block " + nextBlock.getHashAsString()); } // bitcoind doesn't request blocks inline so we can't rely on a ping for synchronization for (int i = 0; !shouldntRequest && !blocksRequested.contains(nextBlock.getHash()); i++) { int SLEEP_TIME = 1; if (i % 1000/SLEEP_TIME == 1000/SLEEP_TIME - 1) log.error("bitcoind still hasn't requested block " + block.ruleName + " with hash " + nextBlock.getHash()); Thread.sleep(SLEEP_TIME); if (i > 60000/SLEEP_TIME) { log.error("bitcoind failed to request block " + block.ruleName); System.exit(1); } } if (shouldntRequest) { Thread.sleep(100); if (blocksRequested.contains(nextBlock.getHash())) { log.error("ERROR: bitcoind re-requested block " + block.ruleName + " with hash " + nextBlock.getHash()); rulesSinceFirstFail++; } } // If the block throws, we may want to get bitcoind to request the same block again if (block.throwsException) blocksRequested.remove(nextBlock.getHash()); //bitcoind.sendMessage(nextBlock); locator = new BlockLocator(); locator = locator.add(bitcoindChainHead); bitcoind.sendMessage(new GetHeadersMessage(PARAMS.getSerializer().getProtocolVersion(), locator, hashTo)); bitcoind.sendPing().get(); if (!chain.getChainHead().getHeader().getHash().equals(bitcoindChainHead)) { rulesSinceFirstFail++; log.error("ERROR: bitcoind and bitcoinj acceptance differs on block \"" + block.ruleName + "\""); } if (block.sendOnce) preloadedBlocks.remove(nextBlock.getHash()); log.info("Block \"" + block.ruleName + "\" completed processing"); } else if (rule instanceof MemoryPoolState) { MemoryPoolMessage message = new MemoryPoolMessage(); bitcoind.sendMessage(message); bitcoind.sendPing().get(); if (mostRecentInv == null && !((MemoryPoolState) rule).mempool.isEmpty()) { log.error("ERROR: bitcoind had an empty mempool, but we expected some transactions on rule " + rule.ruleName); rulesSinceFirstFail++; } else if (mostRecentInv != null && ((MemoryPoolState) rule).mempool.isEmpty()) { log.error("ERROR: bitcoind had a non-empty mempool, but we expected an empty one on rule " + rule.ruleName); rulesSinceFirstFail++; } else if (mostRecentInv != null) { Set<InventoryItem> originalRuleSet = new HashSet<>(((MemoryPoolState)rule).mempool); boolean matches = mostRecentInv.items.size() == ((MemoryPoolState)rule).mempool.size(); for (InventoryItem item : mostRecentInv.items) if (!((MemoryPoolState) rule).mempool.remove(item)) matches = false; if (matches) continue; log.error("bitcoind's mempool didn't match what we were expecting on rule " + rule.ruleName); log.info(" bitcoind's mempool was: "); for (InventoryItem item : mostRecentInv.items) log.info(" " + item.hash); log.info(" The expected mempool was: "); for (InventoryItem item : originalRuleSet) log.info(" " + item.hash); rulesSinceFirstFail++; } mostRecentInv = null; } else { throw new RuntimeException("Unknown rule"); } if (rulesSinceFirstFail > 0) rulesSinceFirstFail++; if (rulesSinceFirstFail > 6) System.exit(1); } if (unexpectedInvs.get() > 0) log.error("ERROR: Got " + unexpectedInvs.get() + " unexpected invs from bitcoind"); log.info("Done testing."); System.exit(rulesSinceFirstFail > 0 || unexpectedInvs.get() > 0 ? 1 : 0); } }
19,323
52.827298
176
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/AddressV2MessageTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.params.TestNet3Params; import org.junit.Test; import java.net.Inet4Address; import java.net.Inet6Address; import java.nio.ByteBuffer; import java.util.List; import org.bitcoinj.base.internal.ByteUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class AddressV2MessageTest { private static final NetworkParameters TESTNET = TestNet3Params.get(); // mostly copied from src/test/netbase_tests.cpp#stream_addrv2_hex and src/test/net_tests.cpp private static final String MESSAGE_HEX = "05" // number of entries + "61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009 + "00" // service flags, COMPACTSIZE(NODE_NONE) + "01" // network id, IPv4 + "04" // address length, COMPACTSIZE(4) + "00000001" // address + "0000" // port + "79627683" // time, Tue Nov 22 11:22:33 UTC 2039 + "01" // service flags, COMPACTSIZE(NODE_NETWORK) + "02" // network id, IPv6 + "10" // address length, COMPACTSIZE(16) + "00000000000000000000000000000001" // address + "00f1" // port + "ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106 + "fd4804" // service flags, COMPACTSIZE(NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED) + "02" // network id, IPv6 + "10" // address length, COMPACTSIZE(16) + "00000000000000000000000000000001" // address + "f1f2" // port + "00000000" // time + "00" // service flags, COMPACTSIZE(NODE_NONE) + "03" // network id, TORv2 + "0a" // address length, COMPACTSIZE(10) + "f1f2f3f4f5f6f7f8f9fa" // address + "0000" // port + "00000000" // time + "00" // service flags, COMPACTSIZE(NODE_NONE) + "04" // network id, TORv3 + "20"// address length, COMPACTSIZE(32) + "53cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88" // address + "0000"; // port @Test public void roundtrip() { AddressMessage message = AddressV2Message.read(ByteBuffer.wrap(ByteUtils.parseHex(MESSAGE_HEX))); List<PeerAddress> addresses = message.getAddresses(); assertEquals(5, addresses.size()); PeerAddress a0 = addresses.get(0); assertEquals("2009-01-09T02:54:25Z", TimeUtils.dateTimeFormat(a0.time())); assertFalse(a0.getServices().hasAny()); assertTrue(a0.getAddr() instanceof Inet4Address); assertEquals("0.0.0.1", a0.getAddr().getHostAddress()); assertNull(a0.getHostname()); assertEquals(0, a0.getPort()); PeerAddress a1 = addresses.get(1); assertEquals("2039-11-22T11:22:33Z", TimeUtils.dateTimeFormat(a1.time())); assertEquals(Services.NODE_NETWORK, a1.getServices().bits()); assertTrue(a1.getAddr() instanceof Inet6Address); assertEquals("0:0:0:0:0:0:0:1", a1.getAddr().getHostAddress()); assertNull(a1.getHostname()); assertEquals(0xf1, a1.getPort()); PeerAddress a2 = addresses.get(2); assertEquals("2106-02-07T06:28:15Z", TimeUtils.dateTimeFormat(a2.time())); assertEquals(Services.NODE_WITNESS | 1 << 6 /* NODE_COMPACT_FILTERS */ | Services.NODE_NETWORK_LIMITED, a2.getServices().bits()); assertTrue(a2.getAddr() instanceof Inet6Address); assertEquals("0:0:0:0:0:0:0:1", a2.getAddr().getHostAddress()); assertNull(a2.getHostname()); assertEquals(0xf1f2, a2.getPort()); PeerAddress a3 = addresses.get(3); assertEquals("1970-01-01T00:00:00Z", TimeUtils.dateTimeFormat(a3.time())); assertFalse(a3.getServices().hasAny()); assertNull(a3.getAddr()); assertEquals("6hzph5hv6337r6p2.onion", a3.getHostname()); assertEquals(0, a3.getPort()); PeerAddress a4 = addresses.get(4); assertEquals("1970-01-01T00:00:00Z", TimeUtils.dateTimeFormat(a4.time())); assertFalse(a4.getServices().hasAny()); assertNull(a4.getAddr()); assertEquals("kpgvmscirrdqpekbqjsvw5teanhatztpp2gl6eee4zkowvwfxwenqaid.onion", a4.getHostname()); assertEquals(0, a4.getPort()); assertEquals(MESSAGE_HEX, ByteUtils.formatHex(message.serialize())); } }
5,420
44.175
120
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/PartialMerkleTreeTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.base.Sha256Hash; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @RunWith(JUnitParamsRunner.class) public class PartialMerkleTreeTest { @Test @Parameters(method = "randomPartialMerkleTrees") public void readAndWrite(PartialMerkleTree pmt) { ByteBuffer buf = ByteBuffer.allocate(pmt.getMessageSize()); pmt.write(buf); assertFalse(buf.hasRemaining()); ((Buffer) buf).rewind(); PartialMerkleTree pmtCopy = PartialMerkleTree.read(buf); assertFalse(buf.hasRemaining()); assertEquals(pmt, pmtCopy); } private Iterator<PartialMerkleTree> randomPartialMerkleTrees() { Random random = new Random(); return Stream.generate(() -> { byte[] randomBits = new byte[random.nextInt(20)]; random.nextBytes(randomBits); List<Sha256Hash> hashes = Stream.generate(() -> { byte[] randomHash = new byte[Sha256Hash.LENGTH]; return Sha256Hash.wrap(randomHash); }).limit(random.nextInt(10)).collect(Collectors.toList()); return new PartialMerkleTree(random.nextInt(20), hashes, randomBits); }).limit(10).iterator(); } }
2,216
34.190476
81
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/ChainSplitTest.java
/* * Copyright 2012 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletTransaction; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.bitcoinj.base.Coin.CENT; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.FIFTY_COINS; import static org.bitcoinj.base.Coin.ZERO; import static org.bitcoinj.base.Coin.valueOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ChainSplitTest { private static final Logger log = LoggerFactory.getLogger(ChainSplitTest.class); private static final NetworkParameters TESTNET = TestNet3Params.get(); private Wallet wallet; private BlockChain chain; private Address coinsTo; private Address coinsTo2; private Address someOtherGuy; @Before public void setUp() throws Exception { BriefLogFormatter.init(); TimeUtils.setMockClock(); // Use mock clock Context.propagate(new Context(100, Coin.ZERO, false, true)); MemoryBlockStore blockStore = new MemoryBlockStore(TESTNET.getGenesisBlock()); wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); ECKey key1 = wallet.freshReceiveKey(); ECKey key2 = wallet.freshReceiveKey(); chain = new BlockChain(TESTNET, wallet, blockStore); coinsTo = key1.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); coinsTo2 = key2.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); someOtherGuy = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); } @Test public void testForking1() throws Exception { // Check that if the block chain forks, we end up using the right chain. Only tests inbound transactions // (receiving coins). Checking that we understand reversed spends is in testForking2. final AtomicBoolean reorgHappened = new AtomicBoolean(); final AtomicInteger walletChanged = new AtomicInteger(); wallet.addReorganizeEventListener(wallet -> reorgHappened.set(true)); wallet.addChangeEventListener(wallet -> walletChanged.incrementAndGet()); // Start by building a couple of blocks on top of the genesis block. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); Block b2 = b1.createNextBlock(coinsTo); assertTrue(chain.add(b1)); assertTrue(chain.add(b2)); Threading.waitForUserCode(); assertFalse(reorgHappened.get()); assertEquals(2, walletChanged.get()); // We got two blocks which sent 50 coins each to us. assertEquals(Coin.valueOf(100, 0), wallet.getBalance()); // We now have the following chain: // genesis -> b1 -> b2 // // so fork like this: // // genesis -> b1 -> b2 // \-> b3 // // Nothing should happen at this point. We saw b2 first so it takes priority. Block b3 = b1.createNextBlock(someOtherGuy); assertTrue(chain.add(b3)); Threading.waitForUserCode(); assertFalse(reorgHappened.get()); // No re-org took place. assertEquals(2, walletChanged.get()); assertEquals(Coin.valueOf(100, 0), wallet.getBalance()); // Check we can handle multi-way splits: this is almost certainly going to be extremely rare, but we have to // handle it anyway. The same transaction appears in b7/b8 (side chain) but not b2 or b3. // genesis -> b1--> b2 // |-> b3 // |-> b7 (x) // \-> b8 (x) Block b7 = b1.createNextBlock(coinsTo); assertTrue(chain.add(b7)); Block b8 = b1.createNextBlock(coinsTo); final Transaction t = b7.getTransactions().get(1); final Sha256Hash tHash = t.getTxId(); b8.addTransaction(t); b8.solve(); assertTrue(chain.add(roundtrip(b8))); Threading.waitForUserCode(); assertEquals(2, wallet.getTransaction(tHash).getAppearsInHashes().size()); assertFalse(reorgHappened.get()); // No re-org took place. assertEquals(5, walletChanged.get()); assertEquals(Coin.valueOf(100, 0), wallet.getBalance()); // Now we add another block to make the alternative chain longer. assertTrue(chain.add(b3.createNextBlock(someOtherGuy))); Threading.waitForUserCode(); assertTrue(reorgHappened.get()); // Re-org took place. assertEquals(6, walletChanged.get()); reorgHappened.set(false); // // genesis -> b1 -> b2 // \-> b3 -> b4 // We lost some coins! b2 is no longer a part of the best chain so our available balance should drop to 50. // It's now pending reconfirmation. assertEquals(FIFTY_COINS, wallet.getBalance()); // ... and back to the first chain. Block b5 = b2.createNextBlock(coinsTo); Block b6 = b5.createNextBlock(coinsTo); assertTrue(chain.add(b5)); assertTrue(chain.add(b6)); // // genesis -> b1 -> b2 -> b5 -> b6 // \-> b3 -> b4 // Threading.waitForUserCode(); assertTrue(reorgHappened.get()); assertEquals(9, walletChanged.get()); assertEquals(Coin.valueOf(200, 0), wallet.getBalance()); } @Test public void testForking2() throws Exception { // Check that if the chain forks and new coins are received in the alternate chain our balance goes up // after the re-org takes place. Block b1 = TESTNET.getGenesisBlock().createNextBlock(someOtherGuy); Block b2 = b1.createNextBlock(someOtherGuy); assertTrue(chain.add(b1)); assertTrue(chain.add(b2)); // genesis -> b1 -> b2 // \-> b3 -> b4 assertEquals(Coin.ZERO, wallet.getBalance()); Block b3 = b1.createNextBlock(coinsTo); Block b4 = b3.createNextBlock(someOtherGuy); assertTrue(chain.add(b3)); assertEquals(Coin.ZERO, wallet.getBalance()); assertTrue(chain.add(b4)); assertEquals(FIFTY_COINS, wallet.getBalance()); } @Test public void testForking3() throws Exception { // Check that we can handle our own spends being rolled back by a fork. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); assertEquals(FIFTY_COINS, wallet.getBalance()); Address dest = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Transaction spend = wallet.createSend(dest, valueOf(10, 0)); wallet.commitTx(spend); // Waiting for confirmation ... make it eligible for selection. assertEquals(Coin.ZERO, wallet.getBalance()); spend.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByAddress(new byte[]{1, 2, 3, 4}), TESTNET.getPort())); spend.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByAddress(new byte[]{5,6,7,8}), TESTNET.getPort())); assertEquals(ConfidenceType.PENDING, spend.getConfidence().getConfidenceType()); assertEquals(valueOf(40, 0), wallet.getBalance()); Block b2 = b1.createNextBlock(someOtherGuy); b2.addTransaction(spend); b2.solve(); chain.add(roundtrip(b2)); // We have 40 coins in change. assertEquals(ConfidenceType.BUILDING, spend.getConfidence().getConfidenceType()); // genesis -> b1 (receive coins) -> b2 (spend coins) // \-> b3 -> b4 Block b3 = b1.createNextBlock(someOtherGuy); Block b4 = b3.createNextBlock(someOtherGuy); chain.add(b3); chain.add(b4); // b4 causes a re-org that should make our spend go pending again. assertEquals(valueOf(40, 0), wallet.getBalance(Wallet.BalanceType.ESTIMATED)); assertEquals(ConfidenceType.PENDING, spend.getConfidence().getConfidenceType()); } @Test public void testForking4() throws Exception { // Check that we can handle external spends on an inactive chain becoming active. An external spend is where // we see a transaction that spends our own coins but we did not broadcast it ourselves. This happens when // keys are being shared between wallets. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); assertEquals(FIFTY_COINS, wallet.getBalance()); Address dest = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Transaction spend = wallet.createSend(dest, FIFTY_COINS); // We do NOT confirm the spend here. That means it's not considered to be pending because createSend is // stateless. For our purposes it is as if some other program with our keys created the tx. // // genesis -> b1 (receive 50) --> b2 // \-> b3 (external spend) -> b4 Block b2 = b1.createNextBlock(someOtherGuy); chain.add(b2); Block b3 = b1.createNextBlock(someOtherGuy); b3.addTransaction(spend); b3.solve(); chain.add(roundtrip(b3)); // The external spend is now pending. assertEquals(ZERO, wallet.getBalance()); Transaction tx = wallet.getTransaction(spend.getTxId()); assertEquals(ConfidenceType.PENDING, tx.getConfidence().getConfidenceType()); Block b4 = b3.createNextBlock(someOtherGuy); chain.add(b4); // The external spend is now active. assertEquals(ZERO, wallet.getBalance()); assertEquals(ConfidenceType.BUILDING, tx.getConfidence().getConfidenceType()); } @Test public void testForking5() throws Exception { // Test the standard case in which a block containing identical transactions appears on a side chain. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); final Transaction t = b1.transactions.get(1); assertEquals(FIFTY_COINS, wallet.getBalance()); // genesis -> b1 // -> b2 Block b2 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); Transaction b2coinbase = b2.transactions.get(0); b2.transactions.clear(); b2.addTransaction(b2coinbase); b2.addTransaction(t); b2.solve(); chain.add(roundtrip(b2)); assertEquals(FIFTY_COINS, wallet.getBalance()); assertTrue(wallet.isConsistent()); assertEquals(2, wallet.getTransaction(t.getTxId()).getAppearsInHashes().size()); // -> b2 -> b3 Block b3 = b2.createNextBlock(someOtherGuy); chain.add(b3); assertEquals(FIFTY_COINS, wallet.getBalance()); } private Block roundtrip(Block b2) throws ProtocolException { return TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(b2.serialize())); } @Test public void testForking6() throws Exception { // Test the case in which a side chain block contains a tx, and then it appears in the best chain too. Block b1 = TESTNET.getGenesisBlock().createNextBlock(someOtherGuy); chain.add(b1); // genesis -> b1 // -> b2 Block b2 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); chain.add(b2); assertEquals(Coin.ZERO, wallet.getBalance()); // genesis -> b1 -> b3 // -> b2 Block b3 = b1.createNextBlock(someOtherGuy); b3.addTransaction(b2.transactions.get(1)); b3.solve(); chain.add(roundtrip(b3)); assertEquals(FIFTY_COINS, wallet.getBalance()); } @Test public void testDoubleSpendOnFork() throws Exception { // Check what happens when a re-org happens and one of our confirmed transactions becomes invalidated by a // double spend on the new best chain. final boolean[] eventCalled = new boolean[1]; wallet.addTransactionConfidenceEventListener((wallet, tx) -> { if (tx.getConfidence().getConfidenceType() == ConfidenceType.DEAD) eventCalled[0] = true; }); Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); Transaction t1 = wallet.createSend(someOtherGuy, valueOf(10, 0)); Address yetAnotherGuy = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Transaction t2 = wallet.createSend(yetAnotherGuy, valueOf(20, 0)); wallet.commitTx(t1); // Receive t1 as confirmed by the network. Block b2 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); b2.addTransaction(t1); b2.solve(); chain.add(roundtrip(b2)); // Now we make a double spend become active after a re-org. Block b3 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); b3.addTransaction(t2); b3.solve(); chain.add(roundtrip(b3)); // Side chain. Block b4 = b3.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); chain.add(b4); // New best chain. Threading.waitForUserCode(); // Should have seen a double spend. assertTrue(eventCalled[0]); assertEquals(valueOf(30, 0), wallet.getBalance()); } @Test public void testDoubleSpendOnForkPending() throws Exception { // Check what happens when a re-org happens and one of our unconfirmed transactions becomes invalidated by a // double spend on the new best chain. final Transaction[] eventDead = new Transaction[1]; final Transaction[] eventReplacement = new Transaction[1]; wallet.addTransactionConfidenceEventListener((wallet, tx) -> { if (tx.getConfidence().getConfidenceType() == ConfidenceType.DEAD) { eventDead[0] = tx; eventReplacement[0] = tx.getConfidence().getOverridingTransaction(); } }); // Start with 50 coins. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); chain.add(b1); Transaction t1 = Objects.requireNonNull(wallet.createSend(someOtherGuy, valueOf(10, 0))); Address yetAnotherGuy = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Transaction t2 = Objects.requireNonNull(wallet.createSend(yetAnotherGuy, valueOf(20, 0))); wallet.commitTx(t1); // t1 is still pending ... Block b2 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); chain.add(b2); assertEquals(ZERO, wallet.getBalance()); assertEquals(valueOf(40, 0), wallet.getBalance(Wallet.BalanceType.ESTIMATED)); // Now we make a double spend become active after a re-org. // genesis -> b1 -> b2 [t1 pending] // \-> b3 (t2) -> b4 Block b3 = b1.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); b3.addTransaction(t2); b3.solve(); chain.add(roundtrip(b3)); // Side chain. Block b4 = b3.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); chain.add(b4); // New best chain. Threading.waitForUserCode(); // Should have seen a double spend against the pending pool. // genesis -> b1 -> b2 [t1 dead and exited the miners mempools] // \-> b3 (t2) -> b4 assertEquals(t1, eventDead[0]); assertEquals(t2, eventReplacement[0]); assertEquals(valueOf(30, 0), wallet.getBalance()); // ... and back to our own parallel universe. Block b5 = b2.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); chain.add(b5); Block b6 = b5.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); chain.add(b6); // genesis -> b1 -> b2 -> b5 -> b6 [t1 still dead] // \-> b3 [t2 resurrected and now pending] -> b4 assertEquals(ZERO, wallet.getBalance()); // t2 is pending - resurrected double spends take precedence over our dead transactions (which are in nobodies // mempool by this point). t1 = Objects.requireNonNull(wallet.getTransaction(t1.getTxId())); t2 = Objects.requireNonNull(wallet.getTransaction(t2.getTxId())); assertEquals(ConfidenceType.DEAD, t1.getConfidence().getConfidenceType()); assertEquals(ConfidenceType.PENDING, t2.getConfidence().getConfidenceType()); } @Test public void txConfidenceLevels() throws Exception { // Check that as the chain forks and re-orgs, the confidence data associated with each transaction is // maintained correctly. final ArrayList<Transaction> txns = new ArrayList<>(3); wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> txns.add(tx)); // Start by building three blocks on top of the genesis block. All send to us. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinsTo); BigInteger work1 = b1.getWork(); Block b2 = b1.createNextBlock(coinsTo2); BigInteger work2 = b2.getWork(); Block b3 = b2.createNextBlock(coinsTo2); BigInteger work3 = b3.getWork(); assertTrue(chain.add(b1)); assertTrue(chain.add(b2)); assertTrue(chain.add(b3)); Threading.waitForUserCode(); // Check the transaction confidence levels are correct. assertEquals(3, txns.size()); assertEquals(1, txns.get(0).getConfidence().getAppearedAtChainHeight()); assertEquals(2, txns.get(1).getConfidence().getAppearedAtChainHeight()); assertEquals(3, txns.get(2).getConfidence().getAppearedAtChainHeight()); assertEquals(3, txns.get(0).getConfidence().getDepthInBlocks()); assertEquals(2, txns.get(1).getConfidence().getDepthInBlocks()); assertEquals(1, txns.get(2).getConfidence().getDepthInBlocks()); // We now have the following chain: // genesis -> b1 -> b2 -> b3 // // so fork like this: // // genesis -> b1 -> b2 -> b3 // \-> b4 -> b5 // // Nothing should happen at this point. We saw b2 and b3 first so it takes priority. Block b4 = b1.createNextBlock(someOtherGuy); BigInteger work4 = b4.getWork(); Block b5 = b4.createNextBlock(someOtherGuy); BigInteger work5 = b5.getWork(); assertTrue(chain.add(b4)); assertTrue(chain.add(b5)); Threading.waitForUserCode(); assertEquals(3, txns.size()); assertEquals(1, txns.get(0).getConfidence().getAppearedAtChainHeight()); assertEquals(2, txns.get(1).getConfidence().getAppearedAtChainHeight()); assertEquals(3, txns.get(2).getConfidence().getAppearedAtChainHeight()); assertEquals(3, txns.get(0).getConfidence().getDepthInBlocks()); assertEquals(2, txns.get(1).getConfidence().getDepthInBlocks()); assertEquals(1, txns.get(2).getConfidence().getDepthInBlocks()); // Now we add another block to make the alternative chain longer. Block b6 = b5.createNextBlock(someOtherGuy); BigInteger work6 = b6.getWork(); assertTrue(chain.add(b6)); // // genesis -> b1 -> b2 -> b3 // \-> b4 -> b5 -> b6 // assertEquals(3, txns.size()); assertEquals(1, txns.get(0).getConfidence().getAppearedAtChainHeight()); assertEquals(4, txns.get(0).getConfidence().getDepthInBlocks()); // Transaction 1 (in block b2) is now on a side chain, so it goes pending (not see in chain). assertEquals(ConfidenceType.PENDING, txns.get(1).getConfidence().getConfidenceType()); try { txns.get(1).getConfidence().getAppearedAtChainHeight(); fail(); } catch (IllegalStateException e) {} assertEquals(0, txns.get(1).getConfidence().getDepthInBlocks()); // ... and back to the first chain. Block b7 = b3.createNextBlock(coinsTo); BigInteger work7 = b7.getWork(); Block b8 = b7.createNextBlock(coinsTo); BigInteger work8 = b7.getWork(); assertTrue(chain.add(b7)); assertTrue(chain.add(b8)); // // genesis -> b1 -> b2 -> b3 -> b7 -> b8 // \-> b4 -> b5 -> b6 // // This should be enabled, once we figure out the best way to inform the user of how the wallet is changing // during the re-org. //assertEquals(5, txns.size()); assertEquals(1, txns.get(0).getConfidence().getAppearedAtChainHeight()); assertEquals(2, txns.get(1).getConfidence().getAppearedAtChainHeight()); assertEquals(3, txns.get(2).getConfidence().getAppearedAtChainHeight()); assertEquals(5, txns.get(0).getConfidence().getDepthInBlocks()); assertEquals(4, txns.get(1).getConfidence().getDepthInBlocks()); assertEquals(3, txns.get(2).getConfidence().getDepthInBlocks()); assertEquals(Coin.valueOf(250, 0), wallet.getBalance()); // Now add two more blocks that don't send coins to us. Despite being irrelevant the wallet should still update. Block b9 = b8.createNextBlock(someOtherGuy); Block b10 = b9.createNextBlock(someOtherGuy); chain.add(b9); chain.add(b10); BigInteger extraWork = b9.getWork().add(b10.getWork()); assertEquals(7, txns.get(0).getConfidence().getDepthInBlocks()); assertEquals(6, txns.get(1).getConfidence().getDepthInBlocks()); assertEquals(5, txns.get(2).getConfidence().getDepthInBlocks()); } @Test public void orderingInsideBlock() throws Exception { // Test that transactions received in the same block have their ordering preserved when reorganising. // This covers issue 468. // Receive some money to the wallet. Transaction t1 = FakeTxBuilder.createFakeTx(TESTNET.network(), COIN, coinsTo); final Block b1 = FakeTxBuilder.makeSolvedTestBlock(TESTNET.getGenesisBlock(), t1); chain.add(b1); // Send a couple of payments one after the other (so the second depends on the change output of the first). Transaction t2 = Objects.requireNonNull(wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), CENT, true)); wallet.commitTx(t2); Transaction t3 = Objects.requireNonNull(wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), CENT, true)); wallet.commitTx(t3); chain.add(FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3)); final Coin coins0point98 = COIN.subtract(CENT).subtract(CENT); assertEquals(coins0point98, wallet.getBalance()); // Now round trip the wallet and force a re-org. ByteArrayOutputStream bos = new ByteArrayOutputStream(); wallet.saveToFileStream(bos); wallet = Wallet.loadFromFileStream(new ByteArrayInputStream(bos.toByteArray())); final Block b2 = FakeTxBuilder.makeSolvedTestBlock(b1, t2, t3); final Block b3 = FakeTxBuilder.makeSolvedTestBlock(b2); chain.add(b2); chain.add(b3); // And verify that the balance is as expected. Because new ECKey() is non-deterministic, if the order // isn't being stored correctly this should fail 50% of the time. assertEquals(coins0point98, wallet.getBalance()); } @Test public void coinbaseDeath() throws Exception { // Check that a coinbase tx is marked as dead after a reorg rather than pending as normal non-double-spent // transactions would be. Also check that a dead coinbase on a sidechain is resurrected if the sidechain // becomes the best chain once more. Finally, check that dependent transactions are killed recursively. final ArrayList<Transaction> txns = new ArrayList<>(3); wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, (wallet, tx, prevBalance, newBalance) -> txns.add(tx)); Block b1 = TESTNET.getGenesisBlock().createNextBlock(someOtherGuy); final ECKey coinsTo2 = wallet.freshReceiveKey(); Block b2 = b1.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, coinsTo2.getPubKey(), 2); Block b3 = b2.createNextBlock(someOtherGuy); log.debug("Adding block b1"); assertTrue(chain.add(b1)); log.debug("Adding block b2"); assertTrue(chain.add(b2)); log.debug("Adding block b3"); assertTrue(chain.add(b3)); // We now have the following chain: // genesis -> b1 -> b2 -> b3 // // Check we have seen the coinbase. assertEquals(1, txns.size()); // Check the coinbase transaction is building and in the unspent pool only. final Transaction coinbase = txns.get(0); assertEquals(ConfidenceType.BUILDING, coinbase.getConfidence().getConfidenceType()); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.PENDING, coinbase.getTxId())); assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.UNSPENT, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.SPENT, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.DEAD, coinbase.getTxId())); // Add blocks to b3 until we can spend the coinbase. Block firstTip = b3; for (int i = 0; i < TESTNET.getSpendableCoinbaseDepth() - 2; i++) { firstTip = firstTip.createNextBlock(someOtherGuy); chain.add(firstTip); } // ... and spend. Transaction fodder = wallet.createSend(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), FIFTY_COINS); wallet.commitTx(fodder); final AtomicBoolean fodderIsDead = new AtomicBoolean(false); fodder.getConfidence().addEventListener(Threading.SAME_THREAD, (confidence, reason) -> fodderIsDead.set(confidence.getConfidenceType() == ConfidenceType.DEAD)); // Fork like this: // // genesis -> b1 -> b2 -> b3 -> [...] // \-> b4 -> b5 -> b6 -> [...] // // The b4/ b5/ b6 is now the best chain Block b4 = b1.createNextBlock(someOtherGuy); Block b5 = b4.createNextBlock(someOtherGuy); Block b6 = b5.createNextBlock(someOtherGuy); log.debug("Adding block b4"); assertTrue(chain.add(b4)); log.debug("Adding block b5"); assertTrue(chain.add(b5)); log.debug("Adding block b6"); assertTrue(chain.add(b6)); Block secondTip = b6; for (int i = 0; i < TESTNET.getSpendableCoinbaseDepth() - 2; i++) { secondTip = secondTip.createNextBlock(someOtherGuy); chain.add(secondTip); } // Transaction 1 (in block b2) is now on a side chain and should have confidence type of dead and be in // the dead pool only. assertEquals(TransactionConfidence.ConfidenceType.DEAD, coinbase.getConfidence().getConfidenceType()); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.PENDING, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.UNSPENT, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.SPENT, coinbase.getTxId())); assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.DEAD, coinbase.getTxId())); assertTrue(fodderIsDead.get()); // ... and back to the first chain. Block b7 = firstTip.createNextBlock(someOtherGuy); Block b8 = b7.createNextBlock(someOtherGuy); log.debug("Adding block b7"); assertTrue(chain.add(b7)); log.debug("Adding block b8"); assertTrue(chain.add(b8)); // // genesis -> b1 -> b2 -> b3 -> [...] -> b7 -> b8 // \-> b4 -> b5 -> b6 -> [...] // // The coinbase transaction should now have confidence type of building once more and in the unspent pool only. assertEquals(TransactionConfidence.ConfidenceType.BUILDING, coinbase.getConfidence().getConfidenceType()); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.PENDING, coinbase.getTxId())); assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.UNSPENT, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.SPENT, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.DEAD, coinbase.getTxId())); // However, fodder is still dead. Bitcoin Core doesn't keep killed transactions around in case they become // valid again later. They are just deleted from the mempool for good. // ... make the side chain dominant again. Block b9 = secondTip.createNextBlock(someOtherGuy); Block b10 = b9.createNextBlock(someOtherGuy); log.debug("Adding block b9"); assertTrue(chain.add(b9)); log.debug("Adding block b10"); assertTrue(chain.add(b10)); // // genesis -> b1 -> b2 -> b3 -> [...] -> b7 -> b8 // \-> b4 -> b5 -> b6 -> [...] -> b9 -> b10 // // The coinbase transaction should now have the confidence type of dead and be in the dead pool only. assertEquals(TransactionConfidence.ConfidenceType.DEAD, coinbase.getConfidence().getConfidenceType()); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.PENDING, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.UNSPENT, coinbase.getTxId())); assertFalse(wallet.poolContainsTxHash(WalletTransaction.Pool.SPENT, coinbase.getTxId())); assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.DEAD, coinbase.getTxId())); } }
31,774
46.567365
168
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/TxConfidenceTableTest.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import org.junit.Before; import org.junit.Test; import java.net.InetAddress; import java.nio.ByteBuffer; import static org.bitcoinj.base.Coin.COIN; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class TxConfidenceTableTest { private static final NetworkParameters TESTNET = TestNet3Params.get(); private Transaction tx1, tx2; private PeerAddress address1, address2, address3; private TxConfidenceTable table; @Before public void setup() throws Exception { BriefLogFormatter.init(); Context context = new Context(); Context.propagate(context); table = context.getConfidenceTable(); Address to = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Address change = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); tx1 = FakeTxBuilder.createFakeTxWithChangeAddress(COIN, to, change); tx2 = FakeTxBuilder.createFakeTxWithChangeAddress(COIN, to, change); assertEquals(tx1.getTxId(), tx2.getTxId()); address1 = PeerAddress.simple(InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), TESTNET.getPort()); address2 = PeerAddress.simple(InetAddress.getByAddress(new byte[] { 127, 0, 0, 2 }), TESTNET.getPort()); address3 = PeerAddress.simple(InetAddress.getByAddress(new byte[] { 127, 0, 0, 3 }), TESTNET.getPort()); } @Test public void pinHandlers() { Transaction tx = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(tx1.serialize())); Sha256Hash hash = tx.getTxId(); table.seen(hash, address1); assertEquals(1, tx.getConfidence().numBroadcastPeers()); final int[] seen = new int[1]; tx.getConfidence().addEventListener(Threading.SAME_THREAD, (confidence, reason) -> seen[0] = confidence.numBroadcastPeers()); tx = null; System.gc(); table.seen(hash, address2); assertEquals(2, seen[0]); } @Test public void events() { final TransactionConfidence.Listener.ChangeReason[] run = new TransactionConfidence.Listener.ChangeReason[1]; tx1.getConfidence().addEventListener(Threading.SAME_THREAD, (confidence, reason) -> run[0] = reason); table.seen(tx1.getTxId(), address1); assertEquals(TransactionConfidence.Listener.ChangeReason.SEEN_PEERS, run[0]); run[0] = null; table.seen(tx1.getTxId(), address1); assertNull(run[0]); } @Test public void testSeen() { PeerAddress peer = createMock(PeerAddress.class); Sha256Hash brokenHash = createMock(Sha256Hash.class); Sha256Hash correctHash = createMock(Sha256Hash.class); TransactionConfidence brokenConfidence = createMock(TransactionConfidence.class); expect(brokenConfidence.getTransactionHash()).andReturn(brokenHash); expect(brokenConfidence.markBroadcastBy(peer)).andThrow(new ArithmeticException("some error")); TransactionConfidence correctConfidence = createMock(TransactionConfidence.class); expect(correctConfidence.getTransactionHash()).andReturn(correctHash); expect(correctConfidence.markBroadcastBy(peer)).andReturn(true); correctConfidence.queueListeners(anyObject(TransactionConfidence.Listener.ChangeReason.class)); expectLastCall(); TransactionConfidence.Factory factory = createMock(TransactionConfidence.Factory.class); expect(factory.createConfidence(brokenHash)).andReturn(brokenConfidence); expect(factory.createConfidence(correctHash)).andReturn(correctConfidence); replay(factory, brokenConfidence, correctConfidence); TxConfidenceTable table = new TxConfidenceTable(1, factory); try { table.seen(brokenHash, peer); } catch (ArithmeticException expected) { // do nothing } assertNotNull(table.seen(correctHash, peer)); } @Test public void invAndDownload() { // Base case: we see a transaction announced twice and then download it. The count is in the confidence object. assertEquals(0, table.numBroadcastPeers(tx1.getTxId())); table.seen(tx1.getTxId(), address1); assertEquals(1, table.numBroadcastPeers(tx1.getTxId())); table.seen(tx1.getTxId(), address2); assertEquals(2, table.numBroadcastPeers(tx1.getTxId())); assertEquals(2, tx2.getConfidence().numBroadcastPeers()); // And now we see another inv. table.seen(tx1.getTxId(), address3); assertEquals(3, tx2.getConfidence().numBroadcastPeers()); assertEquals(3, table.numBroadcastPeers(tx1.getTxId())); } }
5,963
40.706294
133
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/SendHeadersMessageTest.java
/* * Copyright 2017 Anton Kumaigorodski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.io.BaseEncoding; import org.bitcoinj.params.RegTestParams; import org.junit.Test; import java.nio.ByteBuffer; import static org.junit.Assert.assertTrue; public class SendHeadersMessageTest { private static final BaseEncoding HEX = BaseEncoding.base16().lowerCase(); private static final NetworkParameters REGTEST = RegTestParams.get(); @Test public void decodeAndEncode() throws Exception { byte[] message = HEX .decode("00000000fabfb5da73656e646865616465727300000000005df6e0e2fabfb5da70696e670000000000000000080000009a" + "65b9cc9840c9729e4502b200000000000000000000000000000d000000000000000000000000000000000000000000000000007ad82" + "872c28ac782102f5361746f7368693a302e31342e312fe41d000001fabfb5da76657261636b000000000000000000005df6e0e2fabf" + "b5da616c65727400000000000000a80000001bf9aaea60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01fff" + "fff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c207570677261" + "6465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9" + "c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50000000000000000000000000000000000000000000000000"); ByteBuffer buffer = ByteBuffer.wrap(message); BitcoinSerializer serializer = new BitcoinSerializer(REGTEST); assertTrue(serializer.deserialize(buffer) instanceof SendHeadersMessage); } }
2,255
47
137
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/BlockChainTest.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.SigNetParams; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.KeyChainGroup; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.Wallet.BalanceType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.concurrent.CompletableFuture; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.FIFTY_COINS; import static org.bitcoinj.base.Coin.ZERO; import static org.bitcoinj.base.Coin.valueOf; import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock; import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; // Handling of chain splits/reorgs are in ChainSplitTests. public class BlockChainTest { @Rule public ExpectedException thrown = ExpectedException.none(); private Wallet testNetWallet; private MemoryBlockStore testNetStore; private BlockChain testNetChain; private Address coinbaseTo; private static final NetworkParameters TESTNET = TestNet3Params.get(); private static final NetworkParameters SIGNET = SigNetParams.get(); private static final NetworkParameters MAINNET = MainNetParams.get(); @Before public void setUp() throws Exception { BriefLogFormatter.initVerbose(); TimeUtils.setMockClock(); // Use mock clock Context.propagate(new Context(100, Coin.ZERO, false, false)); testNetWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); testNetStore = new MemoryBlockStore(TESTNET.getGenesisBlock()); testNetChain = new BlockChain(TESTNET, testNetWallet, testNetStore); coinbaseTo = testNetWallet.currentReceiveKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); } @Test public void testBasicChaining() throws Exception { // Check that we can plug a few blocks together and the futures work. CompletableFuture<StoredBlock> future = testNetChain.getHeightFuture(2); // Block 1 from the testnet. Block b1 = getBlock1(); assertTrue(testNetChain.add(b1)); assertFalse(future.isDone()); // Block 2 from the testnet. Block b2 = getBlock2(); // Let's try adding an invalid block. long n = b2.getNonce(); try { b2.setNonce(12345); testNetChain.add(b2); fail(); } catch (VerificationException e) { b2.setNonce(n); } // Now it works because we reset the nonce. assertTrue(testNetChain.add(b2)); assertTrue(future.isDone()); assertEquals(2, future.get().getHeight()); } @Test public void receiveCoins() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); int height = 1; // Quick check that we can actually receive coins. Transaction tx1 = createFakeTx(TESTNET.network(), COIN, testNetWallet.currentReceiveKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); Block b1 = createFakeBlock(testNetStore, height, tx1).block; testNetChain.add(b1); assertTrue(testNetWallet.getBalance().signum() > 0); } @Test public void unconnectedBlocks() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinbaseTo); Block b2 = b1.createNextBlock(coinbaseTo); Block b3 = b2.createNextBlock(coinbaseTo); // Connected. assertTrue(testNetChain.add(b1)); // Unconnected but stored. The head of the chain is still b1. assertFalse(testNetChain.add(b3)); assertEquals(testNetChain.getChainHead().getHeader(), b1.cloneAsHeader()); // Add in the middle block. assertTrue(testNetChain.add(b2)); assertEquals(testNetChain.getChainHead().getHeader(), b3.cloneAsHeader()); } // adds 2015 (interval-1) intermediate blocks between the transition points private static void addIntermediteBlocks(BlockChain chain, int epoch, Duration spacing) throws PrunedException { int interval = chain.params.interval; Block prev = chain.getChainHead().getHeader(); // there is an additional spacing here, to account for the fact that for the difficulty adjustment only // interval minus 1 blocks are taken into account Instant newTime = prev.time().plus(spacing); for (int i = 1; i < interval; i++) { newTime = newTime.plus(spacing); Block newBlock = prev.createNextBlock(null, 1, newTime, epoch * interval + i); assertTrue(chain.add(newBlock)); prev = newBlock; } } private static void addTransitionBlock(BlockChain chain, int epoch, Duration spacing) throws PrunedException { int interval = chain.params.interval; Block prev = chain.getChainHead().getHeader(); Instant newTime = prev.time().plus(spacing); Block newBlock = prev.createNextBlock(null, 1, newTime, epoch * interval); assertTrue(chain.add(newBlock)); } @Test public void difficultyTransitions_perfectSpacing() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); BlockChain chain = new BlockChain(MAINNET, new MemoryBlockStore(MAINNET.getGenesisBlock())); // genesis block is already there addIntermediteBlocks(chain, 0, Duration.ofMinutes(10)); addTransitionBlock(chain, 1, Duration.ofMinutes(10)); } @Test(expected = VerificationException.class) public void difficultyTransitions_tooQuick() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); BlockChain chain = new BlockChain(MAINNET, new MemoryBlockStore(MAINNET.getGenesisBlock())); // genesis block is already there addIntermediteBlocks(chain, 0, Duration.ofMinutes(10).minusSeconds(1)); addTransitionBlock(chain, 1, Duration.ofMinutes(10).minusSeconds(1)); } @Test(expected = VerificationException.class) public void difficultyTransitions_tooSlow() throws Exception { // we're using signet because it's not at max target from the start Context.propagate(new Context(100, Coin.ZERO, false, true)); BlockChain chain = new BlockChain(SIGNET, new MemoryBlockStore(SIGNET.getGenesisBlock())); // genesis block is already there addIntermediteBlocks(chain, 0, Duration.ofMinutes(10).plusSeconds(1)); addTransitionBlock(chain, 1, Duration.ofMinutes(10).plusSeconds(1)); } @Test public void difficultyTransitions_tooSlow_butIsAtMax() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); BlockChain chain = new BlockChain(MAINNET, new MemoryBlockStore(MAINNET.getGenesisBlock())); // genesis block is already there addIntermediteBlocks(chain, 0, Duration.ofMinutes(20)); // we can add the transition block with the old target, becuase it is already at the maximum (genesis block) addTransitionBlock(chain, 1, Duration.ofMinutes(20)); } @Test(expected = VerificationException.class) public void difficultyTransitions_unexpectedChange() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); BlockChain chain = new BlockChain(MAINNET, new MemoryBlockStore(MAINNET.getGenesisBlock())); // genesis block is already there Block prev = chain.getChainHead().getHeader(); Instant newTime = prev.time().plus(Duration.ofMinutes(10)); Block newBlock = prev.createNextBlock(null, 1, newTime, 1); newBlock.setDifficultyTarget(newBlock.getDifficultyTarget() + 10); assertTrue(chain.add(newBlock)); } @Test public void badDifficultyTarget() throws Exception { assertTrue(testNetChain.add(getBlock1())); Block b2 = getBlock2(); assertTrue(testNetChain.add(b2)); Block bad = new Block(Block.BLOCK_VERSION_GENESIS); // Merkle root can be anything here, doesn't matter. bad.setMerkleRoot(Sha256Hash.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); // Nonce was just some number that made the hash < difficulty limit set below, it can be anything. bad.setNonce(140548933); bad.setTime(Instant.ofEpochSecond(1279242649)); bad.setPrevBlockHash(b2.getHash()); // We're going to make this block so easy 50% of solutions will pass, and check it gets rejected for having a // bad difficulty target. Unfortunately the encoding mechanism means we cannot make one that accepts all // solutions. bad.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET); try { testNetChain.add(bad); // The difficulty target above should be rejected on the grounds of being easier than the networks // allowable difficulty. fail(); } catch (VerificationException e) { assertTrue(e.getMessage(), e.getCause().getMessage().contains("Difficulty target is out of range")); } } /** * Test that version 2 blocks are rejected once version 3 blocks are a super * majority. */ @Test public void badBip66Version() throws Exception { testDeprecatedBlockVersion(Block.BLOCK_VERSION_BIP34, Block.BLOCK_VERSION_BIP66); } /** * Test that version 3 blocks are rejected once version 4 blocks are a super * majority. */ @Test public void badBip65Version() throws Exception { testDeprecatedBlockVersion(Block.BLOCK_VERSION_BIP66, Block.BLOCK_VERSION_BIP65); } private void testDeprecatedBlockVersion(final long deprecatedVersion, final long newVersion) throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); // Build a historical chain of version 3 blocks Instant time = Instant.ofEpochSecond(1231006505); int height = 0; FakeTxBuilder.BlockPair chainHead = null; // Put in just enough v2 blocks to be a minority for (height = 0; height < (TESTNET.getMajorityWindow() - TESTNET.getMajorityRejectBlockOutdated()); height++) { chainHead = FakeTxBuilder.createFakeBlock(testNetStore, deprecatedVersion, time, height); testNetChain.add(chainHead.block); time = time.plus(1, ChronoUnit.MINUTES); } // Fill the rest of the window with v3 blocks for (; height < TESTNET.getMajorityWindow(); height++) { chainHead = FakeTxBuilder.createFakeBlock(testNetStore, newVersion, time, height); testNetChain.add(chainHead.block); time = time.plus(1, ChronoUnit.MINUTES); } chainHead = FakeTxBuilder.createFakeBlock(testNetStore, deprecatedVersion, time, height); // Trying to add a new v2 block should result in rejection thrown.expect(VerificationException.BlockVersionOutOfDate.class); try { testNetChain.add(chainHead.block); } catch(final VerificationException ex) { throw (Exception) ex.getCause(); } } @Test public void duplicates() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); // Adding a block twice should not have any effect, in particular it should not send the block to the wallet. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinbaseTo); Block b2 = b1.createNextBlock(coinbaseTo); Block b3 = b2.createNextBlock(coinbaseTo); assertTrue(testNetChain.add(b1)); assertEquals(b1, testNetChain.getChainHead().getHeader()); assertTrue(testNetChain.add(b2)); assertEquals(b2, testNetChain.getChainHead().getHeader()); assertTrue(testNetChain.add(b3)); assertEquals(b3, testNetChain.getChainHead().getHeader()); assertTrue(testNetChain.add(b2)); // add old block assertEquals(b3, testNetChain.getChainHead().getHeader()); // block didn't change, duplicate was spotted } @Test public void intraBlockDependencies() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); // Covers issue 166 in which transactions that depend on each other inside a block were not always being // considered relevant. Address somebodyElse = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Block b1 = TESTNET.getGenesisBlock().createNextBlock(somebodyElse); ECKey key = testNetWallet.freshReceiveKey(); Address addr = key.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); // Create a tx that gives us some coins, and another that spends it to someone else in the same block. Transaction t1 = FakeTxBuilder.createFakeTx(TESTNET.network(), COIN, addr); Transaction t2 = new Transaction(); t2.addInput(t1.getOutput(0)); t2.addOutput(valueOf(2, 0), somebodyElse); b1.addTransaction(t1); b1.addTransaction(t2); b1.solve(); testNetChain.add(b1); assertEquals(Coin.ZERO, testNetWallet.getBalance()); } @Test public void coinbaseTransactionAvailability() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); // Check that a coinbase transaction is only available to spend after NetworkParameters.getSpendableCoinbaseDepth() blocks. // Create a second wallet to receive the coinbase spend. Wallet wallet2 = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); ECKey receiveKey = wallet2.freshReceiveKey(); int height = 1; testNetChain.addWallet(wallet2); Address addressToSendTo = receiveKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); // Create a block, sending the coinbase to the coinbaseTo address (which is in the wallet). Block b1 = TESTNET.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, testNetWallet.currentReceiveKey().getPubKey(), height++); testNetChain.add(b1); final Transaction coinbaseTransaction = b1.getTransactions().get(0); // Check a transaction has been received. assertNotNull(coinbaseTransaction); // The coinbase tx is not yet available to spend. assertEquals(Coin.ZERO, testNetWallet.getBalance()); assertEquals(FIFTY_COINS, testNetWallet.getBalance(BalanceType.ESTIMATED)); assertFalse(testNetWallet.isTransactionMature(coinbaseTransaction)); // Attempt to spend the coinbase - this should fail as the coinbase is not mature yet. try { testNetWallet.createSend(addressToSendTo, valueOf(49, 0)); fail(); } catch (InsufficientMoneyException e) { } // Check that the coinbase is unavailable to spend for the next spendableCoinbaseDepth - 2 blocks. for (int i = 0; i < TESTNET.getSpendableCoinbaseDepth() - 2; i++) { // Non relevant tx - just for fake block creation. Transaction tx2 = createFakeTx(TESTNET.network(), COIN, new ECKey().toAddress(ScriptType.P2PKH, TESTNET.network())); Block b2 = createFakeBlock(testNetStore, height++, tx2).block; testNetChain.add(b2); // Wallet still does not have the coinbase transaction available for spend. assertEquals(Coin.ZERO, testNetWallet.getBalance()); assertEquals(FIFTY_COINS, testNetWallet.getBalance(BalanceType.ESTIMATED)); // The coinbase transaction is still not mature. assertFalse(testNetWallet.isTransactionMature(coinbaseTransaction)); // Attempt to spend the coinbase - this should fail. try { testNetWallet.createSend(addressToSendTo, valueOf(49, 0)); fail(); } catch (InsufficientMoneyException e) { } } // Give it one more block - should now be able to spend coinbase transaction. Non relevant tx. Transaction tx3 = createFakeTx(TESTNET.network(), COIN, new ECKey().toAddress(ScriptType.P2PKH, TESTNET.network())); Block b3 = createFakeBlock(testNetStore, height++, tx3).block; testNetChain.add(b3); // Wallet now has the coinbase transaction available for spend. assertEquals(FIFTY_COINS, testNetWallet.getBalance()); assertEquals(FIFTY_COINS, testNetWallet.getBalance(BalanceType.ESTIMATED)); assertTrue(testNetWallet.isTransactionMature(coinbaseTransaction)); // Create a spend with the coinbase BTC to the address in the second wallet - this should now succeed. Transaction coinbaseSend2 = testNetWallet.createSend(addressToSendTo, valueOf(49, 0)); assertNotNull(coinbaseSend2); // Commit the coinbaseSpend to the first wallet and check the balances decrement. testNetWallet.commitTx(coinbaseSend2); assertEquals(COIN, testNetWallet.getBalance(BalanceType.ESTIMATED)); // Available balance is zero as change has not been received from a block yet. assertEquals(ZERO, testNetWallet.getBalance(BalanceType.AVAILABLE)); // Give it one more block - change from coinbaseSpend should now be available in the first wallet. Block b4 = createFakeBlock(testNetStore, height++, coinbaseSend2).block; testNetChain.add(b4); assertEquals(COIN, testNetWallet.getBalance(BalanceType.AVAILABLE)); // Check the balances in the second wallet. assertEquals(valueOf(49, 0), wallet2.getBalance(BalanceType.ESTIMATED)); assertEquals(valueOf(49, 0), wallet2.getBalance(BalanceType.AVAILABLE)); } // Some blocks from the test net. private static Block getBlock2() throws Exception { Block b2 = new Block(Block.BLOCK_VERSION_GENESIS); b2.setMerkleRoot(Sha256Hash.wrap("20222eb90f5895556926c112bb5aa0df4ab5abc3107e21a6950aec3b2e3541e2")); b2.setNonce(875942400L); b2.setTime(Instant.ofEpochSecond(1296688946L)); b2.setDifficultyTarget(0x1d00ffff); b2.setPrevBlockHash(Sha256Hash.wrap("00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206")); assertEquals("000000006c02c8ea6e4ff69651f7fcde348fb9d557a06e6957b65552002a7820", b2.getHashAsString()); Block.verifyHeader(b2); return b2; } private static Block getBlock1() throws Exception { Block b1 = new Block(Block.BLOCK_VERSION_GENESIS); b1.setMerkleRoot(Sha256Hash.wrap("f0315ffc38709d70ad5647e22048358dd3745f3ce3874223c80a7c92fab0c8ba")); b1.setNonce(1924588547); b1.setTime(Instant.ofEpochSecond(1296688928)); b1.setDifficultyTarget(0x1d00ffff); b1.setPrevBlockHash(Sha256Hash.wrap("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943")); assertEquals("00000000b873e79784647a6c82962c70d228557d24a747ea4d1b8bbe878e1206", b1.getHashAsString()); Block.verifyHeader(b1); return b1; } @Test public void estimatedBlockTime() throws Exception { BlockChain prod = new BlockChain(MAINNET, new MemoryBlockStore(MAINNET.getGenesisBlock())); Instant t = prod.estimateBlockTimeInstant(200000); // The actual date of block 200,000 was 2012-09-22 10:47:00 Instant expected = Instant.from(DateTimeFormatter.ISO_INSTANT.parse("2012-10-23T15:35:05Z")); assertEquals(expected, t); } @Test public void falsePositives() { double decay = AbstractBlockChain.FP_ESTIMATOR_ALPHA; assertTrue(0 == testNetChain.getFalsePositiveRate()); // Exactly testNetChain.trackFalsePositives(55); assertEquals(decay * 55, testNetChain.getFalsePositiveRate(), 1e-4); testNetChain.trackFilteredTransactions(550); double rate1 = testNetChain.getFalsePositiveRate(); // Run this scenario a few more time for the filter to converge for (int i = 1 ; i < 10 ; i++) { testNetChain.trackFalsePositives(55); testNetChain.trackFilteredTransactions(550); } // Ensure we are within 10% assertEquals(0.1, testNetChain.getFalsePositiveRate(), 0.01); // Check that we get repeatable results after a reset testNetChain.resetFalsePositiveEstimate(); assertTrue(0 == testNetChain.getFalsePositiveRate()); // Exactly testNetChain.trackFalsePositives(55); assertEquals(decay * 55, testNetChain.getFalsePositiveRate(), 1e-4); testNetChain.trackFilteredTransactions(550); assertEquals(rate1, testNetChain.getFalsePositiveRate(), 1e-4); } @Test public void rollbackBlockStore() throws Exception { Context.propagate(new Context(100, Coin.ZERO, false, true)); // This test simulates an issue on Android, that causes the VM to crash while receiving a block, so that the // block store is persisted but the wallet is not. Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinbaseTo); Block b2 = b1.createNextBlock(coinbaseTo); // Add block 1, no frills. assertTrue(testNetChain.add(b1)); assertEquals(b1.cloneAsHeader(), testNetChain.getChainHead().getHeader()); assertEquals(1, testNetChain.getBestChainHeight()); assertEquals(1, testNetWallet.getLastBlockSeenHeight()); // Add block 2 while wallet is disconnected, to simulate crash. testNetChain.removeWallet(testNetWallet); assertTrue(testNetChain.add(b2)); assertEquals(b2.cloneAsHeader(), testNetChain.getChainHead().getHeader()); assertEquals(2, testNetChain.getBestChainHeight()); assertEquals(1, testNetWallet.getLastBlockSeenHeight()); // Add wallet back. This will detect the height mismatch and repair the damage done. testNetChain.addWallet(testNetWallet); assertEquals(b1.cloneAsHeader(), testNetChain.getChainHead().getHeader()); assertEquals(1, testNetChain.getBestChainHeight()); assertEquals(1, testNetWallet.getLastBlockSeenHeight()); // Now add block 2 correctly. assertTrue(testNetChain.add(b2)); assertEquals(b2.cloneAsHeader(), testNetChain.getChainHead().getHeader()); assertEquals(2, testNetChain.getBestChainHeight()); assertEquals(2, testNetWallet.getLastBlockSeenHeight()); } }
24,112
46.65415
159
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/ProtocolVersionTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test ProtocolVersion */ @RunWith(JUnitParamsRunner.class) public class ProtocolVersionTest { @Test @Parameters(method = "allInstances") public void testValues(ProtocolVersion instance) { assertTrue(instance.intValue() > 0); } @Test @Parameters(method = "allInstances") public void deprecatedMembers(ProtocolVersion instance) { assertEquals(instance.intValue(), instance.getBitcoinProtocolVersion()); } @Test public void deprecatedInstance() { assertEquals(60001, ProtocolVersion.PONG.intValue()); } private ProtocolVersion[] allInstances() { return ProtocolVersion.values(); } }
1,530
27.886792
80
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/ServicesTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.core.Services; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Random; import java.util.stream.LongStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(JUnitParamsRunner.class) public class ServicesTest { @Test public void has() { Services services = Services.of(Services.NODE_BLOOM | Services.NODE_WITNESS); assertTrue(services.has(Services.NODE_BLOOM)); assertTrue(services.has(Services.NODE_WITNESS)); assertTrue(services.has(Services.NODE_BLOOM | Services.NODE_WITNESS)); assertFalse(services.has(Services.NODE_BITCOIN_CASH)); assertFalse(services.has(Services.NODE_BLOOM | Services.NODE_WITNESS | Services.NODE_BITCOIN_CASH)); } @Test public void hasAny_true() { Services services = Services.of(Services.NODE_BLOOM); assertTrue(services.hasAny()); } @Test public void hasAny_false() { Services services = Services.none(); assertFalse(services.hasAny()); } @Test @Parameters(method = "randomLongs") public void readAndWrite(long bits) { Services services = Services.of(bits); ByteBuffer buf = ByteBuffer.allocate(Services.BYTES); services.write(buf); assertFalse(buf.hasRemaining()); ((Buffer) buf).rewind(); Services servicesCopy = Services.read(buf); assertFalse(buf.hasRemaining()); assertEquals(services, servicesCopy); assertEquals(bits, servicesCopy.bits()); } private Iterator<Long> randomLongs() { Random random = new Random(); return LongStream.generate(() -> random.nextLong()).limit(10).iterator(); } }
2,555
32.631579
108
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/FullBlockTestGenerator.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Transaction.SigHash; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.crypto.internal.CryptoUtils; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptPattern; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.time.Period; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Queue; import java.util.Random; import java.util.Set; import static org.bitcoinj.base.Coin.FIFTY_COINS; import static org.bitcoinj.base.Coin.SATOSHI; import static org.bitcoinj.base.Coin.ZERO; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.script.ScriptOpCodes.OP_1; import static org.bitcoinj.script.ScriptOpCodes.OP_2DUP; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIGVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSIG; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSIGVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_ELSE; import static org.bitcoinj.script.ScriptOpCodes.OP_ENDIF; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_FALSE; import static org.bitcoinj.script.ScriptOpCodes.OP_HASH160; import static org.bitcoinj.script.ScriptOpCodes.OP_IF; import static org.bitcoinj.script.ScriptOpCodes.OP_INVALIDOPCODE; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4; import static org.bitcoinj.script.ScriptOpCodes.OP_RETURN; import static org.bitcoinj.script.ScriptOpCodes.OP_TRUE; /** * YOU ARE READING THIS CODE BECAUSE EITHER... * * a) You are testing an alternative implementation with full validation rules. If you are doing this, you should go * rethink your life. Seriously, why are you reimplementing Bitcoin consensus rules? Instead, go work on making * Bitcoin Core consensus rules a shared library and use that. Seriously, you wont get it right, and starting with * this tester as a way to try to do so will simply end in pain and lost coins. SERIOUSLY, JUST STOP! * * b) Bitcoin Core is failing some test in here and you're wondering what test is causing failure. Just stop. There is no * hope trying to read this file and decipher it. Give up and ping BlueMatt. Seriously, this stuff is a huge mess. * * c) You are trying to add a new test. STOP! WHY THE HELL WOULD YOU EVEN DO THAT? GO REWRITE THIS TESTER! * * d) You are BlueMatt and you're trying to hack more crap onto this multi-headed lopsided Proof Of Stake. Why are you * doing this? Seriously, why have you not rewritten this thing yet? WTF man... * * IN ANY CASE, STOP READING NOW. IT WILL SAVE YOU MUCH PAIN AND MISERY LATER */ class NewBlock { public Block block; private TransactionOutPointWithValue spendableOutput; public NewBlock(Block block, TransactionOutPointWithValue spendableOutput) { this.block = block; this.spendableOutput = spendableOutput; } // Wrappers to make it more block-like public Sha256Hash getHash() { return block.getHash(); } public void solve() { block.solve(); } public void addTransaction(Transaction tx) { block.addTransaction(tx); } public TransactionOutPointWithValue getCoinbaseOutput() { return new TransactionOutPointWithValue(block.getTransactions().get(0), 0); } public TransactionOutPointWithValue getSpendableOutput() { return spendableOutput; } } class TransactionOutPointWithValue { public TransactionOutPoint outpoint; public Coin value; public Script scriptPubKey; public TransactionOutPointWithValue(TransactionOutPoint outpoint, Coin value, Script scriptPubKey) { this.outpoint = outpoint; this.value = value; this.scriptPubKey = scriptPubKey; } public TransactionOutPointWithValue(Transaction tx, int outputIndex) { this(new TransactionOutPoint(outputIndex, tx.getTxId()), tx.getOutput(outputIndex).getValue(), tx.getOutput(outputIndex).getScriptPubKey()); } } /** An arbitrary rule which the testing client must match */ class Rule { String ruleName; Rule(String ruleName) { this.ruleName = ruleName; } } /** * A test which checks the mempool state (ie defined which transactions should be in memory pool */ class MemoryPoolState extends Rule { Set<InventoryItem> mempool; public MemoryPoolState(Set<InventoryItem> mempool, String ruleName) { super(ruleName); this.mempool = mempool; } } class RuleList { public List<Rule> list; public int maximumReorgBlockCount; Map<Sha256Hash, Block> hashHeaderMap; public RuleList(List<Rule> list, Map<Sha256Hash, Block> hashHeaderMap, int maximumReorgBlockCount) { this.list = list; this.hashHeaderMap = hashHeaderMap; this.maximumReorgBlockCount = maximumReorgBlockCount; } } public class FullBlockTestGenerator { // Used by BitcoindComparisonTool and AbstractFullPrunedBlockChainTest to create test cases private NetworkParameters params; private ECKey coinbaseOutKey; private byte[] coinbaseOutKeyPubKey; // Used to double-check that we are always using the right next-height private Map<Sha256Hash, Integer> blockToHeightMap = new HashMap<>(); private Map<Sha256Hash, Block> hashHeaderMap = new HashMap<>(); private Map<Sha256Hash, Sha256Hash> coinbaseBlockMap = new HashMap<>(); public FullBlockTestGenerator(NetworkParameters params) { this.params = params; coinbaseOutKey = new ECKey(); coinbaseOutKeyPubKey = coinbaseOutKey.getPubKey(); TimeUtils.setMockClock(); } public RuleList getBlocksToTest(boolean runBarelyExpensiveTests, boolean runExpensiveTests, File blockStorageFile) throws ScriptException, ProtocolException, IOException { final FileOutputStream outStream = blockStorageFile != null ? new FileOutputStream(blockStorageFile) : null; final Script OP_TRUE_SCRIPT = new ScriptBuilder().op(OP_TRUE).build(); final Script OP_NOP_SCRIPT = new ScriptBuilder().op(OP_NOP).build(); // TODO: Rename this variable. List<Rule> blocks = new LinkedList<Rule>() { @Override public boolean add(Rule element) { if (outStream != null && element instanceof BlockAndValidity) { try { ByteUtils.writeInt32BE(params.getPacketMagic(), outStream); byte[] block = ((BlockAndValidity) element).block.serialize(); byte[] length = new byte[4]; ByteUtils.writeInt32LE(block.length, length, 0); outStream.write(length); outStream.write(block); ((BlockAndValidity)element).block = null; } catch (IOException e) { throw new RuntimeException(e); } } return super.add(element); } }; RuleList ret = new RuleList(blocks, hashHeaderMap, 10); Queue<TransactionOutPointWithValue> spendableOutputs = new LinkedList<>(); int chainHeadHeight = 1; Block chainHead = params.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, coinbaseOutKeyPubKey, chainHeadHeight); blocks.add(new BlockAndValidity(chainHead, true, false, chainHead.getHash(), 1, "Initial Block")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(0, chainHead.getTransactions().get(0).getTxId()), FIFTY_COINS, chainHead.getTransactions().get(0).getOutput(0).getScriptPubKey())); for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) { chainHead = chainHead.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, coinbaseOutKeyPubKey, chainHeadHeight); chainHeadHeight++; blocks.add(new BlockAndValidity(chainHead, true, false, chainHead.getHash(), i+1, "Initial Block chain output generation")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(0, chainHead.getTransactions().get(0).getTxId()), FIFTY_COINS, chainHead.getTransactions().get(0).getOutput(0).getScriptPubKey())); } // Start by building a couple of blocks on top of the genesis block. NewBlock b1 = createNextBlock(chainHead, chainHeadHeight + 1, spendableOutputs.poll(), null); blocks.add(new BlockAndValidity(b1, true, false, b1.getHash(), chainHeadHeight + 1, "b1")); spendableOutputs.offer(b1.getCoinbaseOutput()); TransactionOutPointWithValue out1 = spendableOutputs.poll(); checkState(out1 != null); NewBlock b2 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); // Make sure nothing funky happens if we try to re-add b2 blocks.add(new BlockAndValidity(b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); spendableOutputs.offer(b2.getCoinbaseOutput()); // We now have the following chain (which output is spent is in parentheses): // genesis -> b1 (0) -> b2 (1) // // so fork like this: // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) // // Nothing should happen at this point. We saw b2 first so it takes priority. NewBlock b3 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Make sure nothing breaks if we add b3 twice blocks.add(new BlockAndValidity(b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Now we add another block to make the alternative chain longer. // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) -> b4 (2) // TransactionOutPointWithValue out2 = Objects.requireNonNull(spendableOutputs.poll()); NewBlock b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(b4, true, false, b4.getHash(), chainHeadHeight + 3, "b4")); // ... and back to the first chain. NewBlock b5 = createNextBlock(b2, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(b5, true, false, b4.getHash(), chainHeadHeight + 3, "b5")); spendableOutputs.offer(b5.getCoinbaseOutput()); TransactionOutPointWithValue out3 = spendableOutputs.poll(); NewBlock b6 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(b6, true, false, b6.getHash(), chainHeadHeight + 4, "b6")); // // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b3 (1) -> b4 (2) // // Try to create a fork that double-spends // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b7 (2) -> b8 (4) // \-> b3 (1) -> b4 (2) // NewBlock b7 = createNextBlock(b5, chainHeadHeight + 5, out2, null); blocks.add(new BlockAndValidity(b7, true, false, b6.getHash(), chainHeadHeight + 4, "b7")); TransactionOutPointWithValue out4 = spendableOutputs.poll(); NewBlock b8 = createNextBlock(b7, chainHeadHeight + 6, out4, null); blocks.add(new BlockAndValidity(b8, false, true, b6.getHash(), chainHeadHeight + 4, "b8")); // Try to create a block that has too much fee // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b9 (4) // \-> b3 (1) -> b4 (2) // NewBlock b9 = createNextBlock(b6, chainHeadHeight + 5, out4, SATOSHI); blocks.add(new BlockAndValidity(b9, false, true, b6.getHash(), chainHeadHeight + 4, "b9")); // Create a fork that ends in a block with too much fee (the one that causes the reorg) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b10 (3) -> b11 (4) // \-> b3 (1) -> b4 (2) // NewBlock b10 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(b10, true, false, b6.getHash(), chainHeadHeight + 4, "b10")); NewBlock b11 = createNextBlock(b10, chainHeadHeight + 5, out4, SATOSHI); blocks.add(new BlockAndValidity(b11, false, true, b6.getHash(), chainHeadHeight + 4, "b11")); // Try again, but with a valid fork first // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b14 (5) // (b12 added last) // \-> b3 (1) -> b4 (2) // NewBlock b12 = createNextBlock(b5, chainHeadHeight + 4, out3, null); spendableOutputs.offer(b12.getCoinbaseOutput()); NewBlock b13 = createNextBlock(b12, chainHeadHeight + 5, out4, null); blocks.add(new BlockAndValidity(b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); // Make sure we don't die if an orphan gets added twice blocks.add(new BlockAndValidity(b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); spendableOutputs.offer(b13.getCoinbaseOutput()); TransactionOutPointWithValue out5 = spendableOutputs.poll(); NewBlock b14 = createNextBlock(b13, chainHeadHeight + 6, out5, SATOSHI); // This will be "validly" added, though its actually invalid, it will just be marked orphan // and will be discarded when an attempt is made to reorg to it. // TODO: Use a WeakReference to check that it is freed properly after the reorg blocks.add(new BlockAndValidity(b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); // Make sure we don't die if an orphan gets added twice blocks.add(new BlockAndValidity(b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); blocks.add(new BlockAndValidity(b12, false, true, b13.getHash(), chainHeadHeight + 5, "b12")); // Add a block with MAX_BLOCK_SIGOPS and one with one more sigop // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6) // \-> b3 (1) -> b4 (2) // NewBlock b15 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { int sigOps = 0; for (Transaction tx : b15.block.getTransactions()) sigOps += tx.getSigOpCount(); Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b15); b15.addTransaction(tx); sigOps = 0; for (Transaction tx2 : b15.block.getTransactions()) sigOps += tx2.getSigOpCount(); checkState(sigOps == Block.MAX_BLOCK_SIGOPS); } b15.solve(); blocks.add(new BlockAndValidity(b15, true, false, b15.getHash(), chainHeadHeight + 6, "b15")); spendableOutputs.offer(b15.getCoinbaseOutput()); TransactionOutPointWithValue out6 = spendableOutputs.poll(); NewBlock b16 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { int sigOps = 0; for (Transaction tx : b16.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b16); b16.addTransaction(tx); sigOps = 0; for (Transaction tx2 : b16.block.getTransactions()) sigOps += tx2.getSigOpCount(); checkState(sigOps == Block.MAX_BLOCK_SIGOPS + 1); } b16.solve(); blocks.add(new BlockAndValidity(b16, false, true, b15.getHash(), chainHeadHeight + 6, "b16")); // Attempt to spend a transaction created on a different fork // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (6) // \-> b3 (1) -> b4 (2) // NewBlock b17 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, new byte[] {})); addOnlyInputToTransaction(tx, b3); b17.addTransaction(tx); } b17.solve(); blocks.add(new BlockAndValidity(b17, false, true, b15.getHash(), chainHeadHeight + 6, "b17")); // Attempt to spend a transaction created on a different fork (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b18 (5) -> b19 (6) // \-> b3 (1) -> b4 (2) // NewBlock b18 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, new byte[] {})); addOnlyInputToTransaction(tx, b3); b18.addTransaction(tx); } b18.solve(); blocks.add(new BlockAndValidity(b18, true, false, b15.getHash(), chainHeadHeight + 6, "b17")); NewBlock b19 = createNextBlock(b18, chainHeadHeight + 7, out6, null); blocks.add(new BlockAndValidity(b19, false, true, b15.getHash(), chainHeadHeight + 6, "b19")); // Attempt to spend a coinbase at depth too low // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7) // \-> b3 (1) -> b4 (2) // TransactionOutPointWithValue out7 = spendableOutputs.poll(); NewBlock b20 = createNextBlock(b15.block, chainHeadHeight + 7, out7, null); blocks.add(new BlockAndValidity(b20, false, true, b15.getHash(), chainHeadHeight + 6, "b20")); // Attempt to spend a coinbase at depth too low (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b21 (6) -> b22 (5) // \-> b3 (1) -> b4 (2) // NewBlock b21 = createNextBlock(b13, chainHeadHeight + 6, out6, null); blocks.add(new BlockAndValidity(b21.block, true, false, b15.getHash(), chainHeadHeight + 6, "b21")); NewBlock b22 = createNextBlock(b21, chainHeadHeight + 7, out5, null); blocks.add(new BlockAndValidity(b22.block, false, true, b15.getHash(), chainHeadHeight + 6, "b22")); // Create a block on either side of MAX_BLOCK_SIZE and make sure its accepted/rejected // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) // \-> b24 (6) -> b25 (7) // \-> b3 (1) -> b4 (2) // NewBlock b23 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b23.block.messageSize() - 65]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(tx, ZERO, outputScript)); addOnlyInputToTransaction(tx, b23); b23.addTransaction(tx); } b23.solve(); checkState(b23.block.messageSize() == Block.MAX_BLOCK_SIZE); blocks.add(new BlockAndValidity(b23, true, false, b23.getHash(), chainHeadHeight + 7, "b23")); spendableOutputs.offer(b23.getCoinbaseOutput()); NewBlock b24 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b24.block.messageSize() - 64]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(tx, ZERO, outputScript)); addOnlyInputToTransaction(tx, b24); b24.addTransaction(tx); } b24.solve(); checkState(b24.block.messageSize() == Block.MAX_BLOCK_SIZE + 1); blocks.add(new BlockAndValidity(b24, false, true, b23.getHash(), chainHeadHeight + 7, "b24")); // Extend the b24 chain to make sure bitcoind isn't accepting b24 NewBlock b25 = createNextBlock(b24, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(b25, false, false, b23.getHash(), chainHeadHeight + 7, "b25")); // Create blocks with a coinbase input script size out of range // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) // \-> ... (6) -> ... (7) // \-> b3 (1) -> b4 (2) // NewBlock b26 = createNextBlock(b15, chainHeadHeight + 7, out6, null); // 1 is too small, but we already generate every other block with 2, so that is tested b26.block.getTransactions().get(0).getInput(0).clearScriptBytes(); b26.block.setMerkleRoot(null); b26.solve(); blocks.add(new BlockAndValidity(b26, false, true, b23.getHash(), chainHeadHeight + 7, "b26")); // Extend the b26 chain to make sure bitcoind isn't accepting b26 NewBlock b27 = createNextBlock(b26, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(b27, false, false, b23.getHash(), chainHeadHeight + 7, "b27")); NewBlock b28 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { byte[] coinbase = new byte[101]; Arrays.fill(coinbase, (byte)0); b28.block.getTransactions().get(0).getInput(0).setScriptBytes(coinbase); } b28.block.setMerkleRoot(null); b28.solve(); blocks.add(new BlockAndValidity(b28, false, true, b23.getHash(), chainHeadHeight + 7, "b28")); // Extend the b28 chain to make sure bitcoind isn't accepting b28 NewBlock b29 = createNextBlock(b28, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(b29, false, false, b23.getHash(), chainHeadHeight + 7, "b29")); NewBlock b30 = createNextBlock(b23, chainHeadHeight + 8, out7, null); { byte[] coinbase = new byte[100]; Arrays.fill(coinbase, (byte)0); b30.block.getTransactions().get(0).getInput(0).setScriptBytes(coinbase); } b30.block.setMerkleRoot(null); b30.solve(); blocks.add(new BlockAndValidity(b30, true, false, b30.getHash(), chainHeadHeight + 8, "b30")); spendableOutputs.offer(b30.getCoinbaseOutput()); // Check sigops of OP_CHECKMULTISIG/OP_CHECKMULTISIGVERIFY/OP_CHECKSIGVERIFY // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b36 (11) // \-> b34 (10) // \-> b32 (9) // TransactionOutPointWithValue out8 = spendableOutputs.poll(); NewBlock b31 = createNextBlock(b30, chainHeadHeight + 9, out8, null); { int sigOps = 0; for (Transaction tx : b31.block.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b31); b31.addTransaction(tx); } b31.solve(); blocks.add(new BlockAndValidity(b31, true, false, b31.getHash(), chainHeadHeight + 9, "b31")); spendableOutputs.offer(b31.getCoinbaseOutput()); TransactionOutPointWithValue out9 = spendableOutputs.poll(); NewBlock b32 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b32.block.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b32); b32.addTransaction(tx); } b32.solve(); blocks.add(new BlockAndValidity(b32, false, true, b31.getHash(), chainHeadHeight + 9, "b32")); NewBlock b33 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b33.block.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b33); b33.addTransaction(tx); } b33.solve(); blocks.add(new BlockAndValidity(b33, true, false, b33.getHash(), chainHeadHeight + 10, "b33")); spendableOutputs.offer(b33.getCoinbaseOutput()); TransactionOutPointWithValue out10 = spendableOutputs.poll(); NewBlock b34 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b34.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b34); b34.addTransaction(tx); } b34.solve(); blocks.add(new BlockAndValidity(b34, false, true, b33.getHash(), chainHeadHeight + 10, "b34")); NewBlock b35 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b35.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b35); b35.addTransaction(tx); } b35.solve(); blocks.add(new BlockAndValidity(b35, true, false, b35.getHash(), chainHeadHeight + 11, "b35")); spendableOutputs.offer(b35.getCoinbaseOutput()); TransactionOutPointWithValue out11 = spendableOutputs.poll(); NewBlock b36 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { int sigOps = 0; for (Transaction tx : b36.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b36); b36.addTransaction(tx); } b36.solve(); blocks.add(new BlockAndValidity(b36, false, true, b35.getHash(), chainHeadHeight + 11, "b36")); // Check spending of a transaction in a block which failed to connect // (test block store transaction abort handling, not that it should get this far if that's broken...) // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b37 (11) // \-> b38 (11) // NewBlock b37 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, new byte[] {})); addOnlyInputToTransaction(tx, out11); // double spend out11 b37.addTransaction(tx); } b37.solve(); blocks.add(new BlockAndValidity(b37, false, true, b35.getHash(), chainHeadHeight + 11, "b37")); NewBlock b38 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, new byte[] {})); // Attempt to spend b37's first non-coinbase tx, at which point b37 was still considered valid addOnlyInputToTransaction(tx, b37); b38.addTransaction(tx); } b38.solve(); blocks.add(new BlockAndValidity(b38, false, true, b35.getHash(), chainHeadHeight + 11, "b38")); // Check P2SH SigOp counting // 13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b41 (12) // \-> b40 (12) // // Create some P2SH outputs that will require 6 sigops to spend byte[] b39p2shScriptPubKey; int b39numP2SHOutputs = 0, b39sigOpsPerOutput = 6; NewBlock b39 = createNextBlock(b35, chainHeadHeight + 12, null, null); { ByteArrayOutputStream p2shScriptPubKey = new ByteArrayOutputStream(); try { Script.writeBytes(p2shScriptPubKey, coinbaseOutKeyPubKey); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_CHECKSIG); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } b39p2shScriptPubKey = p2shScriptPubKey.toByteArray(); byte[] scriptHash = CryptoUtils.sha256hash160(b39p2shScriptPubKey); ByteArrayOutputStream scriptPubKey = new ByteArrayOutputStream(scriptHash.length + 3); scriptPubKey.write(OP_HASH160); try { Script.writeBytes(scriptPubKey, scriptHash); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } scriptPubKey.write(OP_EQUAL); Coin lastOutputValue = out11.value.subtract(SATOSHI); TransactionOutPoint lastOutPoint; { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(tx, lastOutputValue, new byte[]{OP_1})); addOnlyInputToTransaction(tx, out11); lastOutPoint = new TransactionOutPoint(1, tx.getTxId()); b39.addTransaction(tx); } b39numP2SHOutputs++; while (b39.block.messageSize() < Block.MAX_BLOCK_SIZE) { Transaction tx = new Transaction(); lastOutputValue = lastOutputValue.subtract(SATOSHI); tx.addOutput(new TransactionOutput(tx, SATOSHI, scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(tx, lastOutputValue, new byte[]{OP_1})); tx.addInput(new TransactionInput(tx, new byte[]{OP_1}, lastOutPoint)); lastOutPoint = new TransactionOutPoint(1, tx.getTxId()); if (b39.block.messageSize() + tx.messageSize() < Block.MAX_BLOCK_SIZE) { b39.addTransaction(tx); b39numP2SHOutputs++; } else break; } } b39.solve(); blocks.add(new BlockAndValidity(b39, true, false, b39.getHash(), chainHeadHeight + 12, "b39")); spendableOutputs.offer(b39.getCoinbaseOutput()); TransactionOutPointWithValue out12 = spendableOutputs.poll(); NewBlock b40 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b40.block.getTransactions()) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint(1, b40.block.getTransactions().get(1).getTxId()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, new byte[] {OP_1})); tx.addInput(new TransactionInput(tx, new byte[]{OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(tx, new byte[]{}, new TransactionOutPoint(0, b39.block.getTransactions().get(i).getTxId())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new ByteArrayOutputStream(73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.value); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new ByteArrayOutputStream(signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] {(byte) OP_CHECKSIG}); scriptSigBos.write(Script.createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(0, tx.getTxId()); b40.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(); tx.addInput(new TransactionInput(tx, new byte[]{OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(tx, ZERO, scriptPubKey)); b40.addTransaction(tx); } b40.solve(); blocks.add(new BlockAndValidity(b40, false, true, b39.getHash(), chainHeadHeight + 12, "b40")); NewBlock b41 = null; if (runBarelyExpensiveTests) { b41 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b41.block.getTransactions()) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint( 1, b41.block.getTransactions().get(1).getTxId()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, Coin .SATOSHI, new byte[] {OP_1})); tx.addInput(new TransactionInput(tx, new byte[] { OP_1 }, lastOutPoint)); TransactionInput input = new TransactionInput(tx, new byte[] {}, new TransactionOutPoint(0, b39.block.getTransactions().get(i).getTxId())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new ByteArrayOutputStream( 73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.value); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new ByteArrayOutputStream( signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] { (byte) OP_CHECKSIG}); scriptSigBos.write(Script .createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(0, tx.getTxId()); b41.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(); tx.addInput(new TransactionInput(tx, new byte[] { OP_1 }, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(tx, ZERO, scriptPubKey)); b41.addTransaction(tx); } b41.solve(); blocks.add(new BlockAndValidity(b41, true, false, b41.getHash(), chainHeadHeight + 13, "b41")); } // Fork off of b39 to create a constant base again // b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) // \-> b41 (12) // NewBlock b42 = createNextBlock(b39, chainHeadHeight + 13, out12, null); blocks.add(new BlockAndValidity(b42, true, false, b41 == null ? b42.getHash() : b41.getHash(), chainHeadHeight + 13, "b42")); spendableOutputs.offer(b42.getCoinbaseOutput()); TransactionOutPointWithValue out13 = spendableOutputs.poll(); NewBlock b43 = createNextBlock(b42, chainHeadHeight + 14, out13, null); blocks.add(new BlockAndValidity(b43, true, false, b43.getHash(), chainHeadHeight + 14, "b43")); spendableOutputs.offer(b43.getCoinbaseOutput()); // Test a number of really invalid scenarios // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b44 (14) // \-> ??? (15) // TransactionOutPointWithValue out14 = spendableOutputs.poll(); // A valid block created exactly like b44 to make sure the creation itself works Block b44 = new Block(Block.BLOCK_VERSION_GENESIS); byte[] outScriptBytes = ScriptBuilder.createP2PKOutputScript(ECKey.fromPublicOnly(coinbaseOutKeyPubKey)).program(); { b44.setDifficultyTarget(b43.block.getDifficultyTarget()); b44.addCoinbaseTransaction(coinbaseOutKeyPubKey, ZERO, chainHeadHeight + 15); Transaction t = new Transaction(); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(t, ZERO, new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(t, SATOSHI, outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(t, ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out14); b44.addTransaction(t); b44.setPrevBlockHash(b43.getHash()); b44.setTime(b43.block.time().plusSeconds(1)); } b44.solve(); blocks.add(new BlockAndValidity(b44, true, false, b44.getHash(), chainHeadHeight + 15, "b44")); TransactionOutPointWithValue out15 = spendableOutputs.poll(); // A block with a non-coinbase as the first tx Block b45 = new Block(Block.BLOCK_VERSION_GENESIS); { b45.setDifficultyTarget(b44.getDifficultyTarget()); //b45.addCoinbaseTransaction(pubKey, coinbaseValue); Transaction t = new Transaction(); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(t, ZERO, new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(t, SATOSHI, outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(t, ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out15); try { b45.addTransaction(t); } catch (RuntimeException e) { } // Should happen if (b45.getTransactions().size() > 0) throw new RuntimeException("addTransaction doesn't properly check for adding a non-coinbase as first tx"); b45.addTransaction(t, false); b45.setPrevBlockHash(b44.getHash()); b45.setTime(b44.time().plusSeconds(1)); } b45.solve(); blocks.add(new BlockAndValidity(b45, false, true, b44.getHash(), chainHeadHeight + 15, "b45")); // A block with no txn Block b46 = new Block(Block.BLOCK_VERSION_GENESIS); { b46.transactions = new ArrayList<>(); b46.setDifficultyTarget(b44.getDifficultyTarget()); b46.setMerkleRoot(Sha256Hash.ZERO_HASH); b46.setPrevBlockHash(b44.getHash()); b46.setTime(b44.time().plusSeconds(1)); } b46.solve(); blocks.add(new BlockAndValidity(b46, false, true, b44.getHash(), chainHeadHeight + 15, "b46")); // A block with invalid work NewBlock b47 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { try { // Inverse solve BigInteger target = b47.block.getDifficultyTargetAsInteger(); while (true) { BigInteger h = b47.getHash().toBigInteger(); if (h.compareTo(target) > 0) // if invalid break; // increment the nonce and try again. b47.block.setNonce(b47.block.getNonce() + 1); } } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } blocks.add(new BlockAndValidity(b47, false, true, b44.getHash(), chainHeadHeight + 15, "b47")); // Block with timestamp > 2h in the future NewBlock b48 = createNextBlock(b44, chainHeadHeight + 16, out15, null); b48.block.setTime(TimeUtils.currentTime().plusSeconds(60 * 60 * 3)); b48.solve(); blocks.add(new BlockAndValidity(b48, false, true, b44.getHash(), chainHeadHeight + 15, "b48")); // Block with invalid merkle hash NewBlock b49 = createNextBlock(b44, chainHeadHeight + 16, out15, null); byte[] b49MerkleHash = Sha256Hash.ZERO_HASH.getBytes().clone(); b49MerkleHash[1] = (byte) 0xDE; b49.block.setMerkleRoot(Sha256Hash.of(b49MerkleHash)); b49.solve(); blocks.add(new BlockAndValidity(b49, false, true, b44.getHash(), chainHeadHeight + 15, "b49")); // Block with incorrect POW limit NewBlock b50 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { long diffTarget = b44.getDifficultyTarget(); diffTarget &= 0xFFBFFFFF; // Make difficulty one bit harder b50.block.setDifficultyTarget(diffTarget); } b50.solve(); blocks.add(new BlockAndValidity(b50, false, true, b44.getHash(), chainHeadHeight + 15, "b50")); // A block with two coinbase txn NewBlock b51 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction coinbase = new Transaction(); coinbase.addInput(TransactionInput.coinbaseInput(coinbase, new byte[]{(byte) 0xff, 110, 1})); coinbase.addOutput(new TransactionOutput(coinbase, SATOSHI, outScriptBytes)); b51.block.addTransaction(coinbase, false); } b51.solve(); blocks.add(new BlockAndValidity(b51, false, true, b44.getHash(), chainHeadHeight + 15, "b51")); // A block with duplicate txn NewBlock b52 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, SATOSHI, new byte[] {})); addOnlyInputToTransaction(tx, b52); b52.addTransaction(tx); b52.addTransaction(tx); } b52.solve(); blocks.add(new BlockAndValidity(b52, false, true, b44.getHash(), chainHeadHeight + 15, "b52")); // Test block timestamp // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) // \-> b54 (15) // \-> b44 (14) // NewBlock b53 = createNextBlock(b43, chainHeadHeight + 15, out14, null); blocks.add(new BlockAndValidity(b53, true, false, b44.getHash(), chainHeadHeight + 15, "b53")); spendableOutputs.offer(b53.getCoinbaseOutput()); // Block with invalid timestamp NewBlock b54 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b54.block.setTime(b35.block.time().minusSeconds(1)); b54.solve(); blocks.add(new BlockAndValidity(b54, false, true, b44.getHash(), chainHeadHeight + 15, "b54")); // Block with valid timestamp NewBlock b55 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b55.block.setTime(b35.block.time()); b55.solve(); blocks.add(new BlockAndValidity(b55, true, false, b55.getHash(), chainHeadHeight + 16, "b55")); spendableOutputs.offer(b55.getCoinbaseOutput()); // Test CVE-2012-2459 // -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) // \-> b56 (16) // TransactionOutPointWithValue out16 = spendableOutputs.poll(); NewBlock b57 = createNextBlock(b55, chainHeadHeight + 17, out16, null); Transaction b56txToDuplicate; { b56txToDuplicate = new Transaction(); b56txToDuplicate.addOutput(new TransactionOutput(b56txToDuplicate, SATOSHI, new byte[] {})); addOnlyInputToTransaction(b56txToDuplicate, b57); b57.addTransaction(b56txToDuplicate); } b57.solve(); Block b56; try { b56 = params.getDefaultSerializer().makeBlock(ByteBuffer.wrap(b57.block.serialize())); } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } b56.addTransaction(b56txToDuplicate); checkState(b56.getHash().equals(b57.getHash())); blocks.add(new BlockAndValidity(b56, false, true, b55.getHash(), chainHeadHeight + 16, "b56")); NewBlock b57p2 = createNextBlock(b55, chainHeadHeight + 17, out16, null); Transaction b56p2txToDuplicate1, b56p2txToDuplicate2; { Transaction tx1 = new Transaction(); tx1.addOutput(new TransactionOutput(tx1, SATOSHI, new byte[] {OP_TRUE})); addOnlyInputToTransaction(tx1, b57p2); b57p2.addTransaction(tx1); Transaction tx2 = new Transaction(); tx2.addOutput(new TransactionOutput(tx2, SATOSHI, new byte[] {OP_TRUE})); addOnlyInputToTransaction(tx2, new TransactionOutPointWithValue( new TransactionOutPoint(0, tx1.getTxId()), SATOSHI, tx1.getOutput(0).getScriptPubKey())); b57p2.addTransaction(tx2); b56p2txToDuplicate1 = new Transaction(); b56p2txToDuplicate1.addOutput(new TransactionOutput(b56p2txToDuplicate1, SATOSHI, new byte[]{OP_TRUE})); addOnlyInputToTransaction(b56p2txToDuplicate1, new TransactionOutPointWithValue( new TransactionOutPoint(0, tx2.getTxId()), SATOSHI, tx2.getOutput(0).getScriptPubKey())); b57p2.addTransaction(b56p2txToDuplicate1); b56p2txToDuplicate2 = new Transaction(); b56p2txToDuplicate2.addOutput(new TransactionOutput(b56p2txToDuplicate2, SATOSHI, new byte[]{})); addOnlyInputToTransaction(b56p2txToDuplicate2, new TransactionOutPointWithValue( new TransactionOutPoint(0, b56p2txToDuplicate1.getTxId()), SATOSHI, b56p2txToDuplicate1.getOutput(0).getScriptPubKey())); b57p2.addTransaction(b56p2txToDuplicate2); } b57p2.solve(); Block b56p2; try { b56p2 = params.getDefaultSerializer().makeBlock(ByteBuffer.wrap(b57p2.block.serialize())); } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } b56p2.addTransaction(b56p2txToDuplicate1); b56p2.addTransaction(b56p2txToDuplicate2); checkState(b56p2.getHash().equals(b57p2.getHash())); blocks.add(new BlockAndValidity(b56p2, false, true, b55.getHash(), chainHeadHeight + 16, "b56p2")); blocks.add(new BlockAndValidity(b57p2, true, false, b57p2.getHash(), chainHeadHeight + 17, "b57p2")); blocks.add(new BlockAndValidity(b57, true, false, b57p2.getHash(), chainHeadHeight + 17, "b57")); spendableOutputs.offer(b57.getCoinbaseOutput()); // Test a few invalid tx types // -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> ??? (17) // TransactionOutPointWithValue out17 = spendableOutputs.poll(); // tx with prevout.n out of range NewBlock b58 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, ZERO, new byte[] {})); // Replace the TransactionOutPoint with an out-of-range OutPoint b58.getSpendableOutput().outpoint = new TransactionOutPoint(42, tx); addOnlyInputToTransaction(tx, b58); b58.addTransaction(tx); } b58.solve(); blocks.add(new BlockAndValidity(b58, false, true, b57p2.getHash(), chainHeadHeight + 17, "b58")); // tx with output value > input value out of range NewBlock b59 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, b59.getSpendableOutput().value.add(SATOSHI), new byte[]{})); addOnlyInputToTransaction(tx, b59); b59.addTransaction(tx); } b59.solve(); blocks.add(new BlockAndValidity(b59, false, true, b57p2.getHash(), chainHeadHeight + 17, "b59")); NewBlock b60 = createNextBlock(b57, chainHeadHeight + 18, out17, null); blocks.add(new BlockAndValidity(b60, true, false, b60.getHash(), chainHeadHeight + 18, "b60")); spendableOutputs.offer(b60.getCoinbaseOutput()); // Test BIP30 // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b61 (18) // TransactionOutPointWithValue out18 = spendableOutputs.poll(); NewBlock b61 = createNextBlock(b60, chainHeadHeight + 19, out18, null); { b61.block.getTransactions().get(0).getInput(0).setScriptBytes(b60.block.getTransactions().get(0).getInput(0).getScriptBytes()); b61.block.unCache(); checkState(b61.block.getTransactions().get(0).equals(b60.block.getTransactions().get(0))); } b61.solve(); blocks.add(new BlockAndValidity(b61, false, true, b60.getHash(), chainHeadHeight + 18, "b61")); // Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b62 (18) // NewBlock b62 = createNextBlock(b60, chainHeadHeight + 19, null, null); { Transaction tx = new Transaction(); tx.setLockTime(0xffffffffL); tx.addOutput(ZERO, OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx, out18, 0); b62.addTransaction(tx); checkState(!tx.isFinal(chainHeadHeight + 17, b62.block.getTimeSeconds())); } b62.solve(); blocks.add(new BlockAndValidity(b62, false, true, b60.getHash(), chainHeadHeight + 18, "b62")); // Test a non-final coinbase is also rejected // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b63 (-) // NewBlock b63 = createNextBlock(b60, chainHeadHeight + 19, null, null); { b63.block.getTransactions().get(0).setLockTime(0xffffffffL); b63.block.getTransactions().get(0).getInput(0).setSequenceNumber(0xdeadbeefL); checkState(!b63.block.getTransactions().get(0).isFinal(chainHeadHeight + 17, b63.block.getTimeSeconds())); } b63.solve(); blocks.add(new BlockAndValidity(b63, false, true, b60.getHash(), chainHeadHeight + 18, "b63")); // Check that a block which is (when properly encoded) <= MAX_BLOCK_SIZE is accepted // Even when it is encoded with varints that make its encoded size actually > MAX_BLOCK_SIZE // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) // Block b64; NewBlock b64Original; { b64Original = createNextBlock(b60, chainHeadHeight + 19, out18, null); Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b64Original.block.messageSize() - 65]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(tx, ZERO, outputScript)); addOnlyInputToTransaction(tx, b64Original); b64Original.addTransaction(tx); b64Original.solve(); checkState(b64Original.block.messageSize() == Block.MAX_BLOCK_SIZE); ByteArrayOutputStream stream = new ByteArrayOutputStream(b64Original.block.messageSize() + 8); b64Original.block.writeHeader(stream); byte[] varIntBytes = new byte[9]; varIntBytes[0] = (byte) 255; ByteUtils.writeInt64LE(b64Original.block.getTransactions().size(), varIntBytes, 1); stream.write(varIntBytes); checkState(VarInt.ofBytes(varIntBytes, 0).intValue() == b64Original.block.getTransactions().size()); for (Transaction transaction : b64Original.block.getTransactions()) transaction.bitcoinSerializeToStream(stream); b64 = params.getSerializer().makeBlock(ByteBuffer.wrap(stream.toByteArray())); // The following checks are checking to ensure block serialization functions in the way needed for this test // If they fail, it is likely not an indication of error, but an indication that this test needs rewritten checkState(stream.size() == b64Original.block.messageSize() + 8); // This check fails because it was created for "retain mode" and the likely encoding is not "optimal". // We since removed this capability retain the original encoding, but could not rewrite this test data. // checkState(stream.size() == b64.getMessageSize()); // checkState(Arrays.equals(stream.toByteArray(), b64.bitcoinSerialize())); // checkState(b64.getOptimalEncodingMessageSize() == b64Original.block.getMessageSize()); } blocks.add(new BlockAndValidity(b64, true, false, b64.getHash(), chainHeadHeight + 19, "b64")); spendableOutputs.offer(b64Original.getCoinbaseOutput()); // Spend an output created in the block itself // -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // TransactionOutPointWithValue out19 = spendableOutputs.poll(); checkState(out19 != null);//TODO preconditions all the way up NewBlock b65 = createNextBlock(b64, chainHeadHeight + 20, null, null); { Transaction tx1 = new Transaction(); tx1.addOutput(out19.value, OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx1, out19, 0); b65.addTransaction(tx1); Transaction tx2 = new Transaction(); tx2.addOutput(ZERO, OP_TRUE_SCRIPT); tx2.addInput(tx1.getTxId(), 0, OP_TRUE_SCRIPT); b65.addTransaction(tx2); } b65.solve(); blocks.add(new BlockAndValidity(b65, true, false, b65.getHash(), chainHeadHeight + 20, "b65")); spendableOutputs.offer(b65.getCoinbaseOutput()); // Attempt to spend an output created later in the same block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b66 (20) // TransactionOutPointWithValue out20 = spendableOutputs.poll(); checkState(out20 != null); NewBlock b66 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(); tx1.addOutput(out20.value, OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx1, out20, 0); Transaction tx2 = new Transaction(); tx2.addOutput(ZERO, OP_TRUE_SCRIPT); tx2.addInput(tx1.getTxId(), 0, OP_NOP_SCRIPT); b66.addTransaction(tx2); b66.addTransaction(tx1); } b66.solve(); blocks.add(new BlockAndValidity(b66, false, true, b65.getHash(), chainHeadHeight + 20, "b66")); // Attempt to double-spend a transaction created in a block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b67 (20) // NewBlock b67 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(); tx1.addOutput(out20.value, OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx1, out20, 0); b67.addTransaction(tx1); Transaction tx2 = new Transaction(); tx2.addOutput(ZERO, OP_TRUE_SCRIPT); tx2.addInput(tx1.getTxId(), 0, OP_NOP_SCRIPT); b67.addTransaction(tx2); Transaction tx3 = new Transaction(); tx3.addOutput(out20.value, OP_TRUE_SCRIPT); tx3.addInput(tx1.getTxId(), 0, OP_NOP_SCRIPT); b67.addTransaction(tx3); } b67.solve(); blocks.add(new BlockAndValidity(b67, false, true, b65.getHash(), chainHeadHeight + 20, "b67")); // A few more tests of block subsidy // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b68 (20) // NewBlock b68 = createNextBlock(b65, chainHeadHeight + 21, null, SATOSHI.multiply(10)); { Transaction tx = new Transaction(); tx.addOutput(out20.value.subtract(Coin.valueOf(9)), OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx, out20, 0); b68.addTransaction(tx); } b68.solve(); blocks.add(new BlockAndValidity(b68, false, true, b65.getHash(), chainHeadHeight + 20, "b68")); NewBlock b69 = createNextBlock(b65, chainHeadHeight + 21, null, SATOSHI.multiply(10)); { Transaction tx = new Transaction(); tx.addOutput(out20.value.subtract(Coin.valueOf(10)), OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx, out20, 0); b69.addTransaction(tx); } b69.solve(); blocks.add(new BlockAndValidity(b69, true, false, b69.getHash(), chainHeadHeight + 21, "b69")); spendableOutputs.offer(b69.getCoinbaseOutput()); // Test spending the outpoint of a non-existent transaction // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b70 (21) // TransactionOutPointWithValue out21 = spendableOutputs.poll(); checkState(out21 != null); NewBlock b70 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(); tx.addOutput(ZERO, OP_TRUE_SCRIPT); tx.addInput(Sha256Hash.wrap("23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c"), 0, OP_NOP_SCRIPT); b70.addTransaction(tx); } b70.solve(); blocks.add(new BlockAndValidity(b70, false, true, b69.getHash(), chainHeadHeight + 21, "b70")); // Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks) // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b71 (21) // \-> b72 (21) // NewBlock b72 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(); tx.addOutput(ZERO, OP_TRUE_SCRIPT); addOnlyInputToTransaction(tx, b72); b72.addTransaction(tx); } b72.solve(); Block b71 = params.getDefaultSerializer().makeBlock(ByteBuffer.wrap(b72.block.serialize())); b71.addTransaction(b72.block.getTransactions().get(2)); checkState(b71.getHash().equals(b72.getHash())); blocks.add(new BlockAndValidity(b71, false, true, b69.getHash(), chainHeadHeight + 21, "b71")); blocks.add(new BlockAndValidity(b72, true, false, b72.getHash(), chainHeadHeight + 22, "b72")); spendableOutputs.offer(b72.getCoinbaseOutput()); // Have some fun with invalid scripts and MAX_BLOCK_SIGOPS // -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) // \-> b** (22) // TransactionOutPointWithValue out22 = spendableOutputs.poll(); checkState(out22 != null); NewBlock b73 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b73.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is too large, the CHECKSIGs after that push are still counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; ByteUtils.writeInt32LE(Script.MAX_SCRIPT_ELEMENT_SIZE + 1, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b73); b73.addTransaction(tx); } b73.solve(); blocks.add(new BlockAndValidity(b73, false, true, b72.getHash(), chainHeadHeight + 22, "b73")); NewBlock b74 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b74.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all previous CHECKSIGs are counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xfe; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 5] = (byte)0xff; tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b74); b74.addTransaction(tx); } b74.solve(); blocks.add(new BlockAndValidity(b74, false, true, b72.getHash(), chainHeadHeight + 22, "b74")); NewBlock b75 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b75.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all subsequent CHECKSIGs are not counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b75); b75.addTransaction(tx); } b75.solve(); blocks.add(new BlockAndValidity(b75, true, false, b75.getHash(), chainHeadHeight + 23, "b75")); spendableOutputs.offer(b75.getCoinbaseOutput()); TransactionOutPointWithValue out23 = spendableOutputs.poll(); checkState(out23 != null); NewBlock b76 = createNextBlock(b75, chainHeadHeight + 24, out23, null); { int sigOps = 0; for (Transaction tx : b76.block.getTransactions()) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is filled with CHECKSIGs, they (obviously) arent counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; ByteUtils.writeInt32LE(Block.MAX_BLOCK_SIGOPS, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(tx, SATOSHI, outputScript)); addOnlyInputToTransaction(tx, b76); b76.addTransaction(tx); } b76.solve(); blocks.add(new BlockAndValidity(b76, true, false, b76.getHash(), chainHeadHeight + 24, "b76")); spendableOutputs.offer(b76.getCoinbaseOutput()); // Test transaction resurrection // -> b77 (24) -> b78 (25) -> b79 (26) // \-> b80 (25) -> b81 (26) -> b82 (27) // b78 creates a tx, which is spent in b79. after b82, both should be in mempool // TransactionOutPointWithValue out24 = Objects.requireNonNull(spendableOutputs.poll()); TransactionOutPointWithValue out25 = Objects.requireNonNull(spendableOutputs.poll()); TransactionOutPointWithValue out26 = Objects.requireNonNull(spendableOutputs.poll()); TransactionOutPointWithValue out27 = Objects.requireNonNull(spendableOutputs.poll()); NewBlock b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null); blocks.add(new BlockAndValidity(b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77")); spendableOutputs.offer(b77.getCoinbaseOutput()); NewBlock b78 = createNextBlock(b77, chainHeadHeight + 26, out25, null); Transaction b78tx = new Transaction(); { b78tx.addOutput(ZERO, OP_TRUE_SCRIPT); addOnlyInputToTransaction(b78tx, b77); b78.addTransaction(b78tx); } b78.solve(); blocks.add(new BlockAndValidity(b78, true, false, b78.getHash(), chainHeadHeight + 26, "b78")); NewBlock b79 = createNextBlock(b78, chainHeadHeight + 27, out26, null); Transaction b79tx = new Transaction(); { b79tx.addOutput(ZERO, OP_TRUE_SCRIPT); b79tx.addInput(b78tx.getTxId(), 0, OP_NOP_SCRIPT); b79.addTransaction(b79tx); } b79.solve(); blocks.add(new BlockAndValidity(b79, true, false, b79.getHash(), chainHeadHeight + 27, "b79")); blocks.add(new MemoryPoolState(new HashSet<InventoryItem>(), "post-b79 empty mempool")); NewBlock b80 = createNextBlock(b77, chainHeadHeight + 26, out25, null); blocks.add(new BlockAndValidity(b80, true, false, b79.getHash(), chainHeadHeight + 27, "b80")); spendableOutputs.offer(b80.getCoinbaseOutput()); NewBlock b81 = createNextBlock(b80, chainHeadHeight + 27, out26, null); blocks.add(new BlockAndValidity(b81, true, false, b79.getHash(), chainHeadHeight + 27, "b81")); spendableOutputs.offer(b81.getCoinbaseOutput()); NewBlock b82 = createNextBlock(b81, chainHeadHeight + 28, out27, null); blocks.add(new BlockAndValidity(b82, true, false, b82.getHash(), chainHeadHeight + 28, "b82")); spendableOutputs.offer(b82.getCoinbaseOutput()); HashSet<InventoryItem> post82Mempool = new HashSet<>(); post82Mempool.add(new InventoryItem(InventoryItem.Type.TRANSACTION, b78tx.getTxId())); post82Mempool.add(new InventoryItem(InventoryItem.Type.TRANSACTION, b79tx.getTxId())); blocks.add(new MemoryPoolState(post82Mempool, "post-b82 tx resurrection")); // Test invalid opcodes in dead execution paths. // -> b81 (26) -> b82 (27) -> b83 (28) // b83 creates a tx which contains a transaction script with an invalid opcode in a dead execution path: // OP_FALSE OP_IF OP_INVALIDOPCODE OP_ELSE OP_TRUE OP_ENDIF // TransactionOutPointWithValue out28 = spendableOutputs.poll(); checkState(out28 != null); NewBlock b83 = createNextBlock(b82, chainHeadHeight + 29, null, null); { Transaction tx1 = new Transaction(); tx1.addOutput(new TransactionOutput(tx1, out28.value, new byte[]{OP_IF, (byte) OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF})); addOnlyInputToTransaction(tx1, out28, 0); b83.addTransaction(tx1); Transaction tx2 = new Transaction(); tx2.addOutput(new TransactionOutput(tx2, ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(tx2, new byte[] { OP_FALSE }, new TransactionOutPoint(0, tx1.getTxId()))); b83.addTransaction(tx2); } b83.solve(); blocks.add(new BlockAndValidity(b83, true, false, b83.getHash(), chainHeadHeight + 29, "b83")); spendableOutputs.offer(b83.getCoinbaseOutput()); // Reorg on/off blocks that have OP_RETURN in them (and try to spend them) // -> b81 (26) -> b82 (27) -> b83 (28) -> b84 (29) -> b87 (30) -> b88 (31) // \-> b85 (29) -> b86 (30) \-> b89 (32) // TransactionOutPointWithValue out29 = spendableOutputs.poll(); checkState(out29 != null); TransactionOutPointWithValue out30 = spendableOutputs.poll(); checkState(out30 != null); TransactionOutPointWithValue out31 = spendableOutputs.poll(); checkState(out31 != null); TransactionOutPointWithValue out32 = spendableOutputs.poll(); checkState(out32 != null); NewBlock b84 = createNextBlock(b83, chainHeadHeight + 30, out29, null); Transaction b84tx1 = new Transaction(); { b84tx1.addOutput(new TransactionOutput(b84tx1, ZERO, new byte[]{OP_RETURN})); b84tx1.addOutput(new TransactionOutput(b84tx1, ZERO, new byte[]{OP_TRUE})); b84tx1.addOutput(new TransactionOutput(b84tx1, ZERO, new byte[]{OP_TRUE})); b84tx1.addOutput(new TransactionOutput(b84tx1, ZERO, new byte[]{OP_TRUE})); b84tx1.addOutput(new TransactionOutput(b84tx1, ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(b84tx1, b84); b84.addTransaction(b84tx1); Transaction tx2 = new Transaction(); tx2.addOutput(new TransactionOutput(tx2, ZERO, new byte[]{OP_RETURN})); tx2.addOutput(new TransactionOutput(tx2, ZERO, new byte[]{OP_RETURN})); tx2.addInput(new TransactionInput(tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(1, b84tx1))); b84.addTransaction(tx2); Transaction tx3 = new Transaction(); tx3.addOutput(new TransactionOutput(tx3, ZERO, new byte[]{OP_RETURN})); tx3.addOutput(new TransactionOutput(tx3, ZERO, new byte[]{OP_TRUE})); tx3.addInput(new TransactionInput(tx3, new byte[]{OP_TRUE}, new TransactionOutPoint(2, b84tx1))); b84.addTransaction(tx3); Transaction tx4 = new Transaction(); tx4.addOutput(new TransactionOutput(tx4, ZERO, new byte[]{OP_TRUE})); tx4.addOutput(new TransactionOutput(tx4, ZERO, new byte[]{OP_RETURN})); tx4.addInput(new TransactionInput(tx4, new byte[]{OP_TRUE}, new TransactionOutPoint(3, b84tx1))); b84.addTransaction(tx4); Transaction tx5 = new Transaction(); tx5.addOutput(new TransactionOutput(tx5, ZERO, new byte[]{OP_RETURN})); tx5.addInput(new TransactionInput(tx5, new byte[]{OP_TRUE}, new TransactionOutPoint(4, b84tx1))); b84.addTransaction(tx5); } b84.solve(); blocks.add(new BlockAndValidity(b84, true, false, b84.getHash(), chainHeadHeight + 30, "b84")); spendableOutputs.offer(b84.getCoinbaseOutput()); NewBlock b85 = createNextBlock(b83, chainHeadHeight + 30, out29, null); blocks.add(new BlockAndValidity(b85, true, false, b84.getHash(), chainHeadHeight + 30, "b85")); NewBlock b86 = createNextBlock(b85, chainHeadHeight + 31, out30, null); blocks.add(new BlockAndValidity(b86, true, false, b86.getHash(), chainHeadHeight + 31, "b86")); NewBlock b87 = createNextBlock(b84, chainHeadHeight + 31, out30, null); blocks.add(new BlockAndValidity(b87, true, false, b86.getHash(), chainHeadHeight + 31, "b87")); spendableOutputs.offer(b87.getCoinbaseOutput()); NewBlock b88 = createNextBlock(b87, chainHeadHeight + 32, out31, null); blocks.add(new BlockAndValidity(b88, true, false, b88.getHash(), chainHeadHeight + 32, "b88")); spendableOutputs.offer(b88.getCoinbaseOutput()); NewBlock b89 = createNextBlock(b88, chainHeadHeight + 33, out32, null); { Transaction tx = new Transaction(); tx.addOutput(new TransactionOutput(tx, ZERO, new byte[] {OP_TRUE})); tx.addInput(new TransactionInput(tx, new byte[]{OP_TRUE}, new TransactionOutPoint(0, b84tx1))); b89.addTransaction(tx); b89.solve(); } blocks.add(new BlockAndValidity(b89, false, true, b88.getHash(), chainHeadHeight + 32, "b89")); // The remaining tests arent designed to fit in the standard flow, and thus must always come last // Add new tests here. //TODO: Explicitly address MoneyRange() checks if (!runBarelyExpensiveTests) { if (outStream != null) outStream.close(); // (finally) return the created chain return ret; } // Test massive reorgs (in terms of block count/size) // -> b81 (26) -> b82 (27) -> b83 (28) -> b84 (29) -> b87 (30) -> b88 (31) -> lots of blocks -> b1000 // \-> b85 (29) -> b86 (30) \-> lots more blocks // NewBlock largeReorgFinal; int LARGE_REORG_SIZE = 1008; // +/- a week of blocks int largeReorgLastHeight = chainHeadHeight + 33 + LARGE_REORG_SIZE + 1; { NewBlock nextBlock = b88; int nextHeight = chainHeadHeight + 33; TransactionOutPointWithValue largeReorgOutput = out32; for (int i = 0; i < LARGE_REORG_SIZE; i++) { nextBlock = createNextBlock(nextBlock, nextHeight, largeReorgOutput, null); Transaction tx = new Transaction(); byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - nextBlock.block.messageSize() - 65]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(tx, ZERO, outputScript)); addOnlyInputToTransaction(tx, nextBlock); nextBlock.addTransaction(tx); nextBlock.solve(); blocks.add(new BlockAndValidity(nextBlock, true, false, nextBlock.getHash(), nextHeight++, "large reorg initial blocks " + i)); spendableOutputs.offer(nextBlock.getCoinbaseOutput()); largeReorgOutput = spendableOutputs.poll(); } NewBlock reorgBase = b88; int reorgBaseHeight = chainHeadHeight + 33; for (int i = 0; i < LARGE_REORG_SIZE; i++) { reorgBase = createNextBlock(reorgBase, reorgBaseHeight++, null, null); blocks.add(new BlockAndValidity(reorgBase, true, false, nextBlock.getHash(), nextHeight - 1, "large reorg reorg block " + i)); } reorgBase = createNextBlock(reorgBase, reorgBaseHeight, null, null); blocks.add(new BlockAndValidity(reorgBase, true, false, reorgBase.getHash(), reorgBaseHeight, "large reorg reorging block")); nextBlock = createNextBlock(nextBlock, nextHeight, null, null); blocks.add(new BlockAndValidity(nextBlock, true, false, reorgBase.getHash(), nextHeight++, "large reorg second reorg initial")); spendableOutputs.offer(nextBlock.getCoinbaseOutput()); nextBlock = createNextBlock(nextBlock, nextHeight, null, null); spendableOutputs.poll(); blocks.add(new BlockAndValidity(nextBlock, true, false, nextBlock.getHash(), nextHeight++, "large reorg second reorg")); spendableOutputs.offer(nextBlock.getCoinbaseOutput()); largeReorgFinal = nextBlock; } ret.maximumReorgBlockCount = Math.max(ret.maximumReorgBlockCount, LARGE_REORG_SIZE + 2); // Test massive reorgs (in terms of tx count) // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> lots of outputs -> lots of spends // Reorg back to: // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> empty blocks // NewBlock b1001 = createNextBlock(largeReorgFinal, largeReorgLastHeight + 1, spendableOutputs.poll(), null); blocks.add(new BlockAndValidity(b1001, true, false, b1001.getHash(), largeReorgLastHeight + 1, "b1001")); spendableOutputs.offer(b1001.getCoinbaseOutput()); int heightAfter1001 = largeReorgLastHeight + 2; if (runExpensiveTests) { // No way you can fit this test in memory checkArgument(blockStorageFile != null); NewBlock lastBlock = b1001; TransactionOutPoint lastOutput = new TransactionOutPoint(1, b1001.block.getTransactions().get(1).getTxId()); int blockCountAfter1001; int nextHeight = heightAfter1001; List<Sha256Hash> hashesToSpend = new LinkedList<>(); // all index 0 final int TRANSACTION_CREATION_BLOCKS = 100; for (blockCountAfter1001 = 0; blockCountAfter1001 < TRANSACTION_CREATION_BLOCKS; blockCountAfter1001++) { NewBlock block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.block.messageSize() < Block.MAX_BLOCK_SIZE - 500) { Transaction tx = new Transaction(); tx.addInput(lastOutput.hash(), lastOutput.index(), OP_NOP_SCRIPT); tx.addOutput(ZERO, OP_TRUE_SCRIPT); tx.addOutput(ZERO, OP_TRUE_SCRIPT); lastOutput = new TransactionOutPoint(1, tx.getTxId()); hashesToSpend.add(tx.getTxId()); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction generator " + blockCountAfter1001 + "/" + TRANSACTION_CREATION_BLOCKS).setSendOnce(true)); lastBlock = block; } Iterator<Sha256Hash> hashes = hashesToSpend.iterator(); for (int i = 0; hashes.hasNext(); i++) { NewBlock block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.block.messageSize() < Block.MAX_BLOCK_SIZE - 500 && hashes.hasNext()) { Transaction tx = new Transaction(); tx.addInput(hashes.next(), 0, OP_NOP_SCRIPT); tx.addOutput(ZERO, OP_TRUE_SCRIPT); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction spender " + i).setSendOnce(true)); lastBlock = block; blockCountAfter1001++; } // Reorg back to b1001 + empty blocks Sha256Hash firstHash = lastBlock.getHash(); int height = nextHeight-1; nextHeight = heightAfter1001; lastBlock = b1001; for (int i = 0; i < blockCountAfter1001; i++) { NewBlock block = createNextBlock(lastBlock, nextHeight++, null, null); blocks.add(new BlockAndValidity(block, true, false, firstHash, height, "post-b1001 empty reorg block " + i + "/" + blockCountAfter1001)); lastBlock = block; } // Try to spend from the other chain NewBlock b1002 = createNextBlock(lastBlock, nextHeight, null, null); { Transaction tx = new Transaction(); tx.addInput(hashesToSpend.get(0), 0, OP_NOP_SCRIPT); tx.addOutput(ZERO, OP_TRUE_SCRIPT); b1002.addTransaction(tx); } b1002.solve(); blocks.add(new BlockAndValidity(b1002, false, true, firstHash, height, "b1002")); // Now actually reorg NewBlock b1003 = createNextBlock(lastBlock, nextHeight, null, null); blocks.add(new BlockAndValidity(b1003, true, false, b1003.getHash(), nextHeight, "b1003")); // Now try to spend again NewBlock b1004 = createNextBlock(b1003, nextHeight + 1, null, null); { Transaction tx = new Transaction(); tx.addInput(hashesToSpend.get(0), 0, OP_NOP_SCRIPT); tx.addOutput(ZERO, OP_TRUE_SCRIPT); b1004.addTransaction(tx); } b1004.solve(); blocks.add(new BlockAndValidity(b1004, false, true, b1003.getHash(), nextHeight, "b1004")); ret.maximumReorgBlockCount = Math.max(ret.maximumReorgBlockCount, blockCountAfter1001); } if (outStream != null) outStream.close(); // (finally) return the created chain return ret; } private byte uniquenessCounter = 0; private NewBlock createNextBlock(Block baseBlock, int nextBlockHeight, @Nullable TransactionOutPointWithValue prevOut, Coin additionalCoinbaseValue) throws ScriptException { Integer height = blockToHeightMap.get(baseBlock.getHash()); if (height != null) checkState(height == nextBlockHeight - 1); Coin coinbaseValue = FIFTY_COINS.shiftRight(nextBlockHeight / params.getSubsidyDecreaseBlockCount()) .add((prevOut != null ? prevOut.value.subtract(SATOSHI) : ZERO)) .add(additionalCoinbaseValue == null ? ZERO : additionalCoinbaseValue); Block block = baseBlock.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, coinbaseOutKeyPubKey, coinbaseValue, nextBlockHeight); Transaction t = new Transaction(); if (prevOut != null) { // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(t, ZERO, new byte[] {(byte)(new Random().nextInt() & 0xff), uniquenessCounter++})); // Spendable output t.addOutput(new TransactionOutput(t, SATOSHI, new byte[] {OP_1})); addOnlyInputToTransaction(t, prevOut); block.addTransaction(t); block.solve(); } return new NewBlock(block, prevOut == null ? null : new TransactionOutPointWithValue(t, 1)); } private NewBlock createNextBlock(NewBlock baseBlock, int nextBlockHeight, @Nullable TransactionOutPointWithValue prevOut, Coin additionalCoinbaseValue) throws ScriptException { return createNextBlock(baseBlock.block, nextBlockHeight, prevOut, additionalCoinbaseValue); } private void addOnlyInputToTransaction(Transaction t, NewBlock block) throws ScriptException { addOnlyInputToTransaction(t, block.getSpendableOutput(), TransactionInput.NO_SEQUENCE); } private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut) throws ScriptException { addOnlyInputToTransaction(t, prevOut, TransactionInput.NO_SEQUENCE); } private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut, long sequence) throws ScriptException { TransactionInput input = new TransactionInput(t, new byte[]{}, prevOut.outpoint); input.setSequenceNumber(sequence); t.addInput(input); if (prevOut.scriptPubKey.chunks().get(0).equalsOpCode(OP_TRUE)) { input.setScriptSig(new ScriptBuilder().op(OP_1).build()); } else { // Sign input checkState(ScriptPattern.isP2PK(prevOut.scriptPubKey)); Sha256Hash hash = t.hashForSignature(0, prevOut.scriptPubKey, SigHash.ALL, false); input.setScriptSig(ScriptBuilder.createInputScript( new TransactionSignature(coinbaseOutKey.sign(hash), SigHash.ALL, false)) ); } } /** * Represents a block which is sent to the tested application and which the application must either reject or accept, * depending on the flags in the rule */ class BlockAndValidity extends Rule { Block block; Sha256Hash blockHash; boolean connects; boolean throwsException; boolean sendOnce; // We can throw away the memory for this block once we send it the first time (if bitcoind asks again, its broken) Sha256Hash hashChainTipAfterBlock; int heightAfterBlock; public BlockAndValidity(Block block, boolean connects, boolean throwsException, Sha256Hash hashChainTipAfterBlock, int heightAfterBlock, String blockName) { super(blockName); if (connects && throwsException) throw new RuntimeException("A block cannot connect if an exception was thrown while adding it."); this.block = block; this.blockHash = block.getHash(); this.connects = connects; this.throwsException = throwsException; this.hashChainTipAfterBlock = hashChainTipAfterBlock; this.heightAfterBlock = heightAfterBlock; // Keep track of the set of blocks indexed by hash hashHeaderMap.put(block.getHash(), block.cloneAsHeader()); // Double-check that we are always marking any given block at the same height Integer height = blockToHeightMap.get(hashChainTipAfterBlock); if (height != null) checkState(height == heightAfterBlock); else blockToHeightMap.put(hashChainTipAfterBlock, heightAfterBlock); } public BlockAndValidity(NewBlock block, boolean connects, boolean throwsException, Sha256Hash hashChainTipAfterBlock, int heightAfterBlock, String blockName) { this(block.block, connects, throwsException, hashChainTipAfterBlock, heightAfterBlock, blockName); coinbaseBlockMap.put(block.getCoinbaseOutput().outpoint.hash(), block.getHash()); Integer blockHeight = blockToHeightMap.get(block.block.getPrevBlockHash()); if (blockHeight != null) { blockHeight++; for (Transaction t : block.block.getTransactions()) for (TransactionInput in : t.getInputs()) { Sha256Hash blockSpendingHash = coinbaseBlockMap.get(in.getOutpoint().hash()); checkState(blockSpendingHash == null || blockToHeightMap.get(blockSpendingHash) == null || blockToHeightMap.get(blockSpendingHash) == blockHeight - params.getSpendableCoinbaseDepth()); } } } public BlockAndValidity setSendOnce(boolean sendOnce) { this.sendOnce = sendOnce; return this; } } }
96,323
50.48263
175
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/BloomFilterTest.java
/* * Copyright 2012 Matt Corallo * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.DumpedPrivateKey; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.wallet.KeyChainGroup; import org.bitcoinj.wallet.Wallet; import org.junit.Test; import org.bitcoinj.base.internal.ByteUtils; import java.nio.ByteBuffer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BloomFilterTest { private static final NetworkParameters MAINNET = MainNetParams.get(); @Test public void insertSerializeTest() { BloomFilter filter = new BloomFilter(3, 0.01, 0, BloomFilter.BloomUpdate.UPDATE_ALL); filter.insert(ByteUtils.parseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")); assertTrue (filter.contains(ByteUtils.parseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"))); // One bit different in first byte assertFalse(filter.contains(ByteUtils.parseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8"))); filter.insert(ByteUtils.parseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")); assertTrue(filter.contains(ByteUtils.parseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"))); filter.insert(ByteUtils.parseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")); assertTrue(filter.contains(ByteUtils.parseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"))); // Value generated by Bitcoin Core assertEquals("03614e9b050000000000000001", ByteUtils.formatHex(filter.serialize())); } @Test public void insertSerializeTestWithTweak() { BloomFilter filter = new BloomFilter(3, 0.01, 0x80000001); filter.insert(ByteUtils.parseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")); assertTrue (filter.contains(ByteUtils.parseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"))); // One bit different in first byte assertFalse(filter.contains(ByteUtils.parseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8"))); filter.insert(ByteUtils.parseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")); assertTrue(filter.contains(ByteUtils.parseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"))); filter.insert(ByteUtils.parseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")); assertTrue(filter.contains(ByteUtils.parseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"))); // Value generated by Bitcoin Core assertEquals("03ce4299050000000100008002", ByteUtils.formatHex(filter.serialize())); } @Test public void walletTest() { Context.propagate(new Context()); DumpedPrivateKey privKey = DumpedPrivateKey.fromBase58(BitcoinNetwork.MAINNET, "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"); Address addr = privKey.getKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.MAINNET); assertEquals("17Wx1GQfyPTNWpQMHrTwRSMTCAonSiZx9e", addr.toString()); KeyChainGroup group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).build(); // Add a random key which happens to have been used in a recent generation group.importKeys(ECKey.fromPublicOnly(privKey.getKey()), ECKey.fromPublicOnly(ByteUtils.parseHex("03cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99"))); Wallet wallet = new Wallet(BitcoinNetwork.MAINNET, group); wallet.commitTx(Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0d038754030114062f503253482fffffffff01c05e559500000000232103cb219f69f1b49468bd563239a86667e74a06fcba69ac50a08a5cbc42a5808e99ac00000000")))); // We should have 2 per pubkey, and one for the P2PK output we have assertEquals(5, wallet.getBloomFilterElementCount()); BloomFilter filter = wallet.getBloomFilter(wallet.getBloomFilterElementCount(), 0.001, 0); // Value generated by Bitcoin Core assertEquals("082ae5edc8e51d4a03080000000000000002", ByteUtils.formatHex(filter.serialize())); } }
4,867
46.262136
299
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/MemoryFullPrunedBlockChainTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.FullPrunedBlockStore; import org.bitcoinj.store.MemoryFullPrunedBlockStore; /** * A MemoryStore implementation of the FullPrunedBlockStoreTest */ public class MemoryFullPrunedBlockChainTest extends AbstractFullPrunedBlockChainTest { @Override public FullPrunedBlockStore createStore(NetworkParameters params, int blockCount) throws BlockStoreException { return new MemoryFullPrunedBlockStore(params, blockCount); } @Override public void resetStore(FullPrunedBlockStore store) throws BlockStoreException { //No-op for memory store, because it's not persistent } }
1,330
32.275
112
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/TransactionInputTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.collect.Lists; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @RunWith(JUnitParamsRunner.class) public class TransactionInputTest { private static final NetworkParameters TESTNET = TestNet3Params.get(); @Before public void setUp() throws Exception { Context.propagate(new Context()); } @Test public void testStandardWalletDisconnect() throws Exception { Wallet w = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); Address a = w.currentReceiveAddress(); Transaction tx1 = FakeTxBuilder.createFakeTxWithoutChangeAddress(Coin.COIN, a); w.receivePending(tx1, null); Transaction tx2 = new Transaction(); tx2.addOutput(Coin.valueOf(99000000), new ECKey()); SendRequest req = SendRequest.forTx(tx2); req.allowUnconfirmed(); w.completeTx(req); TransactionInput txInToDisconnect = tx2.getInput(0); assertEquals(tx1, txInToDisconnect.getOutpoint().fromTx); assertNull(txInToDisconnect.getOutpoint().connectedOutput); txInToDisconnect.disconnect(); assertNull(txInToDisconnect.getOutpoint().fromTx); assertNull(txInToDisconnect.getOutpoint().connectedOutput); } @Test public void testUTXOWalletDisconnect() throws Exception { Wallet w = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); Address a = w.currentReceiveAddress(); final UTXO utxo = new UTXO(Sha256Hash.of(new byte[] { 1, 2, 3 }), 1, Coin.COIN, 0, false, ScriptBuilder.createOutputScript(a)); w.setUTXOProvider(new UTXOProvider() { @Override public Network network() { return BitcoinNetwork.TESTNET; } @Override public List<UTXO> getOpenTransactionOutputs(List<ECKey> addresses) throws UTXOProviderException { return Lists.newArrayList(utxo); } @Override public int getChainHeadHeight() throws UTXOProviderException { return Integer.MAX_VALUE; } }); Transaction tx2 = new Transaction(); tx2.addOutput(Coin.valueOf(99000000), new ECKey()); w.completeTx(SendRequest.forTx(tx2)); TransactionInput txInToDisconnect = tx2.getInput(0); assertNull(txInToDisconnect.getOutpoint().fromTx); assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash()); txInToDisconnect.disconnect(); assertNull(txInToDisconnect.getOutpoint().fromTx); assertNull(txInToDisconnect.getOutpoint().connectedOutput); } @Test public void coinbaseInput() { TransactionInput coinbaseInput = TransactionInput.coinbaseInput(new Transaction(), new byte[2]); assertTrue(coinbaseInput.isCoinBase()); } @Test @Parameters(method = "randomInputs") public void readAndWrite(TransactionInput input) { ByteBuffer buf = ByteBuffer.allocate(input.getMessageSize()); input.write(buf); assertFalse(buf.hasRemaining()); ((Buffer) buf).rewind(); TransactionInput inputCopy = TransactionInput.read(buf, input.getParentTransaction()); assertFalse(buf.hasRemaining()); assertEquals(input, inputCopy); } private Iterator<TransactionInput> randomInputs() { Random random = new Random(); Transaction parent = new Transaction(); return Stream.generate(() -> { byte[] randomBytes = new byte[100]; random.nextBytes(randomBytes); return new TransactionInput(parent, randomBytes, TransactionOutPoint.UNCONNECTED, Coin.ofSat(Math.abs(random.nextLong()))); }).limit(10).iterator(); } @Test(expected = IllegalArgumentException.class) public void negativeValue() { new TransactionInput(new Transaction(), new byte[0], TransactionOutPoint.UNCONNECTED, Coin.ofSat(-1)); } }
5,582
35.253247
112
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/AddressV1MessageTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.params.TestNet3Params; import org.junit.Test; import java.net.Inet4Address; import java.net.Inet6Address; import java.nio.ByteBuffer; import java.util.List; import org.bitcoinj.base.internal.ByteUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class AddressV1MessageTest { private static final NetworkParameters TESTNET = TestNet3Params.get(); // mostly copied from src/test/netbase_tests.cpp#stream_addrv1_hex and src/test/net_tests.cpp private static final String MESSAGE_HEX = "04" // number of entries + "61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009 + "0000000000000000" // service flags, NODE_NONE + "00000000000000000000ffff00000001" // address, fixed 16 bytes (IPv4 embedded in IPv6) + "0000" // port + "79627683" // time, Tue Nov 22 11:22:33 UTC 2039 + "0100000000000000" // service flags, NODE_NETWORK + "00000000000000000000000000000001" // address, fixed 16 bytes (IPv6) + "00f1" // port + "ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106 + "4804000000000000" // service flags, NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED + "00000000000000000000000000000001" // address, fixed 16 bytes (IPv6) + "f1f2" // port + "00000000" // time + "0000000000000000" // service flags, NODE_NONE + "fd87d87eeb43f1f2f3f4f5f6f7f8f9fa" // address, fixed 16 bytes (TORv2) + "0000"; // port @Test public void roundtrip() { AddressMessage message = AddressV1Message.read(ByteBuffer.wrap(ByteUtils.parseHex(MESSAGE_HEX))); List<PeerAddress> addresses = message.getAddresses(); assertEquals(4, addresses.size()); PeerAddress a0 = addresses.get(0); assertEquals("2009-01-09T02:54:25Z", TimeUtils.dateTimeFormat(a0.time())); assertFalse(a0.getServices().hasAny()); assertTrue(a0.getAddr() instanceof Inet4Address); assertEquals("0.0.0.1", a0.getAddr().getHostAddress()); assertNull(a0.getHostname()); assertEquals(0, a0.getPort()); PeerAddress a1 = addresses.get(1); assertEquals("2039-11-22T11:22:33Z", TimeUtils.dateTimeFormat(a1.time())); assertEquals(Services.NODE_NETWORK, a1.getServices().bits()); assertTrue(a1.getAddr() instanceof Inet6Address); assertEquals("0:0:0:0:0:0:0:1", a1.getAddr().getHostAddress()); assertNull(a1.getHostname()); assertEquals(0xf1, a1.getPort()); PeerAddress a2 = addresses.get(2); assertEquals("2106-02-07T06:28:15Z", TimeUtils.dateTimeFormat(a2.time())); assertEquals(Services.NODE_WITNESS | 1 << 6 /* NODE_COMPACT_FILTERS */ | Services.NODE_NETWORK_LIMITED, a2.getServices().bits()); assertTrue(a2.getAddr() instanceof Inet6Address); assertEquals("0:0:0:0:0:0:0:1", a2.getAddr().getHostAddress()); assertNull(a2.getHostname()); assertEquals(0xf1f2, a2.getPort()); PeerAddress a3 = addresses.get(3); assertEquals("1970-01-01T00:00:00Z", TimeUtils.dateTimeFormat(a3.time())); assertFalse(a3.getServices().hasAny()); assertNull(a3.getAddr()); assertEquals("6hzph5hv6337r6p2.onion", a3.getHostname()); assertEquals(0, a3.getPort()); assertEquals(MESSAGE_HEX, ByteUtils.formatHex(message.serialize())); } }
4,422
43.676768
117
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/FeeFilterMessageTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.base.Coin; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.junit.Assert.assertEquals; /** * Test FeeFilterMessage */ @RunWith(JUnitParamsRunner.class) public class FeeFilterMessageTest { @Test @Parameters(method = "validFeeRates") public void roundTripValid(Coin feeRate) { byte[] buf = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(feeRate.getValue()).array(); FeeFilterMessage ffm = FeeFilterMessage.read(ByteBuffer.wrap(buf)); assertEquals(feeRate, ffm.feeRate()); byte[] serialized = ffm.serialize(); FeeFilterMessage ffm2 = FeeFilterMessage.read(ByteBuffer.wrap(serialized)); assertEquals(feeRate, ffm2.feeRate()); } @Test(expected = ProtocolException.class) @Parameters(method = "invalidFeeRates") public void invalid(Coin feeRate) { byte[] buf = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(feeRate.getValue()).array(); FeeFilterMessage ffm = FeeFilterMessage.read(ByteBuffer.wrap(buf)); } private Coin[] validFeeRates() { return new Coin[] { Coin.ZERO, Coin.SATOSHI, Coin.FIFTY_COINS, Coin.valueOf(Long.MAX_VALUE) }; } private Coin[] invalidFeeRates() { return new Coin[] { Coin.NEGATIVE_SATOSHI, Coin.valueOf(Integer.MIN_VALUE), Coin.valueOf(Long.MIN_VALUE) }; } }
2,173
34.064516
120
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/TransactionOutputTest.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.testing.TestWithWallet; import org.bitcoinj.wallet.SendRequest; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(JUnitParamsRunner.class) public class TransactionOutputTest extends TestWithWallet { @Before public void setUp() throws Exception { super.setUp(); } @After public void tearDown() throws Exception { super.tearDown(); } @Test public void testMultiSigOutputToString() throws Exception { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN); ECKey myKey = new ECKey(); this.wallet.importKey(myKey); // Simulate another signatory ECKey otherKey = new ECKey(); // Create multi-sig transaction Transaction multiSigTransaction = new Transaction(); List<ECKey> keys = Arrays.asList(myKey, otherKey); Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys); multiSigTransaction.addOutput(Coin.COIN, scriptPubKey); SendRequest req = SendRequest.forTx(multiSigTransaction); this.wallet.completeTx(req); TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0); assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG")); } @Test public void testP2SHOutputScript() { String P2SHAddressString = "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"; Address P2SHAddress = LegacyAddress.fromBase58(P2SHAddressString, BitcoinNetwork.MAINNET); Script script = ScriptBuilder.createOutputScript(P2SHAddress); Transaction tx = new Transaction(); tx.addOutput(Coin.COIN, script); assertEquals(P2SHAddressString, tx.getOutput(0).getScriptPubKey().getToAddress(BitcoinNetwork.MAINNET).toString()); } @Test public void getAddressTests() { Transaction tx = new Transaction(); tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hello world!".getBytes())); assertTrue(ScriptPattern.isOpReturn(tx.getOutput(0).getScriptPubKey())); assertFalse(ScriptPattern.isP2PK(tx.getOutput(0).getScriptPubKey())); assertFalse(ScriptPattern.isP2PKH(tx.getOutput(0).getScriptPubKey())); } @Test public void getMinNonDustValue() { TransactionOutput p2pk = new TransactionOutput(null, Coin.COIN, myKey); assertEquals(Coin.valueOf(576), p2pk.getMinNonDustValue()); TransactionOutput p2pkh = new TransactionOutput(null, Coin.COIN, myKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); assertEquals(Coin.valueOf(546), p2pkh.getMinNonDustValue()); TransactionOutput p2wpkh = new TransactionOutput(null, Coin.COIN, myKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)); assertEquals(Coin.valueOf(294), p2wpkh.getMinNonDustValue()); } @Test public void toString_() { TransactionOutput p2pk = new TransactionOutput(null, Coin.COIN, myKey); p2pk.toString(); TransactionOutput p2pkh = new TransactionOutput(null, Coin.COIN, myKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); p2pkh.toString(); TransactionOutput p2wpkh = new TransactionOutput(null, Coin.COIN, myKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)); p2wpkh.toString(); } @Test @Parameters(method = "randomOutputs") public void write(TransactionOutput output) { ByteBuffer buf = ByteBuffer.allocate(output.getMessageSize()); output.write(buf); assertFalse(buf.hasRemaining()); } private Iterator<TransactionOutput> randomOutputs() { Random random = new Random(); Transaction parent = new Transaction(); return Stream.generate(() -> { byte[] randomBytes = new byte[100]; random.nextBytes(randomBytes); return new TransactionOutput(parent, Coin.ofSat(Math.abs(random.nextLong())), randomBytes); }).limit(10).iterator(); } @Test public void negativeValue_minusOne() { // -1 is allowed because it is used as a sentinel value new TransactionOutput(new Transaction(), Coin.ofSat(-1), new byte[0]); } @Test(expected = IllegalArgumentException.class) public void negativeValue() { new TransactionOutput(new Transaction(), Coin.ofSat(-2), new byte[0]); } }
5,927
36.518987
123
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/TransactionTest.java
/* * Copyright 2014 Google Inc. * Copyright 2016 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.crypto.internal.CryptoUtils; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptError; import org.bitcoinj.script.ScriptException; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.wallet.Wallet; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.IntFunction; import java.util.stream.Stream; import org.bitcoinj.base.internal.ByteUtils; import static org.bitcoinj.base.internal.ByteUtils.writeInt32LE; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Just check the Transaction.verify() method. Most methods that have complicated logic in Transaction are tested * elsewhere, e.g. signing and hashing are well exercised by the wallet tests, the full block chain tests and so on. * The verify method is also exercised by the full block chain tests, but it can also be used by API users alone, * so we make sure to cover it here as well. */ public class TransactionTest { private static final NetworkParameters TESTNET = TestNet3Params.get(); private static final Address ADDRESS = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); @Before public void setUp() { Context.propagate(new Context()); } @Test(expected = VerificationException.EmptyInputsOrOutputs.class) public void emptyOutputs() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.clearOutputs(); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.EmptyInputsOrOutputs.class) public void emptyInputs() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.clearInputs(); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.LargerThanMaxBlockSize.class) public void tooHuge() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.getInput(0).setScriptBytes(new byte[Block.MAX_BLOCK_SIZE]); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.DuplicatedOutPoint.class) public void duplicateOutPoint() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); TransactionInput input = tx.getInput(0); input.setScriptBytes(new byte[1]); tx.addInput(input); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.NegativeValueOutput.class) public void negativeOutput() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.getOutput(0).setValue(Coin.NEGATIVE_SATOSHI); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.ExcessiveValue.class) public void exceedsMaxMoney2() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); Coin half = BitcoinNetwork.MAX_MONEY.divide(2).add(Coin.SATOSHI); tx.getOutput(0).setValue(half); tx.addOutput(half, ADDRESS); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.UnexpectedCoinbaseInput.class) public void coinbaseInputInNonCoinbaseTX() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.addInput(Sha256Hash.ZERO_HASH, 0xFFFFFFFFL, new ScriptBuilder().data(new byte[10]).build()); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.CoinbaseScriptSizeOutOfRange.class) public void coinbaseScriptSigTooSmall() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.clearInputs(); tx.addInput(Sha256Hash.ZERO_HASH, 0xFFFFFFFFL, new ScriptBuilder().build()); Transaction.verify(TESTNET.network(), tx); } @Test(expected = VerificationException.CoinbaseScriptSizeOutOfRange.class) public void coinbaseScriptSigTooLarge() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.clearInputs(); TransactionInput input = tx.addInput(Sha256Hash.ZERO_HASH, 0xFFFFFFFFL, new ScriptBuilder().data(new byte[99]).build()); assertEquals(101, input.getScriptBytes().length); Transaction.verify(TESTNET.network(), tx); } @Test public void testEstimatedLockTime_WhenParameterSignifiesBlockHeight() { int TEST_LOCK_TIME = 20; Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); BlockChain mockBlockChain = createMock(BlockChain.class); EasyMock.expect(mockBlockChain.estimateBlockTimeInstant(TEST_LOCK_TIME)).andReturn(now); Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.setLockTime(TEST_LOCK_TIME); // less than five hundred million replay(mockBlockChain); assertEquals(tx.estimateUnlockTime(mockBlockChain), now); } @Test public void testMessageSize() { Transaction tx = new Transaction(); int length = tx.messageSize(); // add fake transaction input TransactionInput input = new TransactionInput(null, ScriptBuilder.createEmpty().program(), new TransactionOutPoint(0, Sha256Hash.ZERO_HASH)); tx.addInput(input); length += input.getMessageSize(); // add fake transaction output TransactionOutput output = new TransactionOutput(null, Coin.COIN, ADDRESS); tx.addOutput(output); length += output.getMessageSize(); // message size has now grown assertEquals(length, tx.messageSize()); } @Test public void testIsMatureReturnsFalseIfTransactionIsCoinbaseAndConfidenceTypeIsNotEqualToBuilding() { Wallet wallet = Wallet.createBasic(BitcoinNetwork.TESTNET); Transaction tx = FakeTxBuilder.createFakeCoinbaseTx(); tx.getConfidence().setConfidenceType(ConfidenceType.UNKNOWN); assertFalse(wallet.isTransactionMature(tx)); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); assertFalse(wallet.isTransactionMature(tx)); tx.getConfidence().setConfidenceType(ConfidenceType.DEAD); assertFalse(wallet.isTransactionMature(tx)); } @Test public void addSignedInput_P2PKH() { final Address toAddr = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); final Sha256Hash utxo_id = Sha256Hash.wrap("81b4c832d70cb56ff957589752eb4125a4cab78a25a8fc52d6a09e5bd4404d48"); final Coin inAmount = Coin.ofSat(91234); final Coin outAmount = Coin.ofSat(91234); ECKey fromKey = new ECKey(); Address fromAddress = fromKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Transaction tx = new Transaction(); TransactionOutPoint outPoint = new TransactionOutPoint(0, utxo_id); TransactionOutput output = new TransactionOutput(null, inAmount, fromAddress); tx.addOutput(outAmount, toAddr); TransactionInput input = tx.addSignedInput(outPoint, ScriptBuilder.createOutputScript(fromAddress), inAmount, fromKey); // verify signature input.getScriptSig().correctlySpends(tx, 0, null, null, ScriptBuilder.createOutputScript(fromAddress), null); byte[] rawTx = tx.serialize(); assertNotNull(rawTx); } @Test public void addSignedInput_P2WPKH() { final Address toAddr = new ECKey().toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET); final Sha256Hash utxo_id = Sha256Hash.wrap("81b4c832d70cb56ff957589752eb4125a4cab78a25a8fc52d6a09e5bd4404d48"); final Coin inAmount = Coin.ofSat(91234); final Coin outAmount = Coin.ofSat(91234); ECKey fromKey = new ECKey(); Address fromAddress = fromKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET); Transaction tx = new Transaction(); TransactionOutPoint outPoint = new TransactionOutPoint(0, utxo_id); tx.addOutput(outAmount, toAddr); TransactionInput input = tx.addSignedInput(outPoint, ScriptBuilder.createOutputScript(fromAddress), inAmount, fromKey); // verify signature input.getScriptSig().correctlySpends(tx, 0, input.getWitness(), input.getValue(), ScriptBuilder.createOutputScript(fromAddress), null); byte[] rawTx = tx.serialize(); assertNotNull(rawTx); } @Test public void witnessTransaction() { String hex; Transaction tx; // Roundtrip without witness hex = "0100000003362c10b042d48378b428d60c5c98d8b8aca7a03e1a2ca1048bfd469934bbda95010000008b483045022046c8bc9fb0e063e2fc8c6b1084afe6370461c16cbf67987d97df87827917d42d022100c807fa0ab95945a6e74c59838cc5f9e850714d8850cec4db1e7f3bcf71d5f5ef0141044450af01b4cc0d45207bddfb47911744d01f768d23686e9ac784162a5b3a15bc01e6653310bdd695d8c35d22e9bb457563f8de116ecafea27a0ec831e4a3e9feffffffffc19529a54ae15c67526cc5e20e535973c2d56ef35ff51bace5444388331c4813000000008b48304502201738185959373f04cc73dbbb1d061623d51dc40aac0220df56dabb9b80b72f49022100a7f76bde06369917c214ee2179e583fefb63c95bf876eb54d05dfdf0721ed772014104e6aa2cf108e1c650e12d8dd7ec0a36e478dad5a5d180585d25c30eb7c88c3df0c6f5fd41b3e70b019b777abd02d319bf724de184001b3d014cb740cb83ed21a6ffffffffbaae89b5d2e3ca78fd3f13cf0058784e7c089fb56e1e596d70adcfa486603967010000008b483045022055efbaddb4c67c1f1a46464c8f770aab03d6b513779ad48735d16d4c5b9907c2022100f469d50a5e5556fc2c932645f6927ac416aa65bc83d58b888b82c3220e1f0b73014104194b3f8aa08b96cae19b14bd6c32a92364bea3051cb9f018b03e3f09a57208ff058f4b41ebf96b9911066aef3be22391ac59175257af0984d1432acb8f2aefcaffffffff0340420f00000000001976a914c0fbb13eb10b57daa78b47660a4ffb79c29e2e6b88ac204e0000000000001976a9142cae94ffdc05f8214ccb2b697861c9c07e3948ee88ac1c2e0100000000001976a9146e03561cd4d6033456cc9036d409d2bf82721e9888ac00000000"; tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(hex))); assertFalse(tx.hasWitnesses()); assertEquals(3, tx.getInputs().size()); for (TransactionInput in : tx.getInputs()) assertFalse(in.hasWitness()); assertEquals(3, tx.getOutputs().size()); assertEquals(hex, ByteUtils.formatHex(tx.serialize())); assertEquals("Uncorrect hash", "38d4cfeb57d6685753b7a3b3534c3cb576c34ca7344cd4582f9613ebf0c2b02a", tx.getTxId().toString()); assertEquals(tx.getWTxId(), tx.getTxId()); assertEquals(hex.length() / 2, tx.messageSize()); // Roundtrip with witness hex = "0100000000010213206299feb17742091c3cb2ab45faa3aa87922d3c030cafb3f798850a2722bf0000000000feffffffa12f2424b9599898a1d30f06e1ce55eba7fabfeee82ae9356f07375806632ff3010000006b483045022100fcc8cf3014248e1a0d6dcddf03e80f7e591605ad0dbace27d2c0d87274f8cd66022053fcfff64f35f22a14deb657ac57f110084fb07bb917c3b42e7d033c54c7717b012102b9e4dcc33c9cc9cb5f42b96dddb3b475b067f3e21125f79e10c853e5ca8fba31feffffff02206f9800000000001976a9144841b9874d913c430048c78a7b18baebdbea440588ac8096980000000000160014e4873ef43eac347471dd94bc899c51b395a509a502483045022100dd8250f8b5c2035d8feefae530b10862a63030590a851183cb61b3672eb4f26e022057fe7bc8593f05416c185d829b574290fb8706423451ebd0a0ae50c276b87b43012102179862f40b85fa43487500f1d6b13c864b5eb0a83999738db0f7a6b91b2ec64f00db080000"; tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(hex))); assertTrue(tx.hasWitnesses()); assertEquals(2, tx.getInputs().size()); assertTrue(tx.getInput(0).hasWitness()); assertFalse(tx.getInput(1).hasWitness()); assertEquals(2, tx.getOutputs().size()); assertEquals(hex, ByteUtils.formatHex(tx.serialize())); assertEquals("Uncorrect hash", "99e7484eafb6e01622c395c8cae7cb9f8822aab6ba993696b39df8b60b0f4b11", tx.getTxId().toString()); assertNotEquals(tx.getWTxId(), tx.getTxId()); assertEquals(hex.length() / 2, tx.messageSize()); } @Test public void testWitnessSignatureP2WPKH() { // test vector P2WPKH from: // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki String txHex = "01000000" // version + "02" // num txIn + "fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f" + "00000000" + "00" + "eeffffff" // txIn + "ef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a" + "01000000" + "00" + "ffffffff" // txIn + "02" // num txOut + "202cb20600000000" + "1976a914" + "8280b37df378db99f66f85c95a783a76ac7a6d59" + "88ac" // txOut + "9093510d00000000" + "1976a914" + "3bde42dbee7e4dbe6a21b2d50ce2f0167faa8159" + "88ac" // txOut + "11000000"; // nLockTime Transaction tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(txHex))); assertEquals(txHex, ByteUtils.formatHex(tx.serialize())); assertEquals(txHex.length() / 2, tx.messageSize()); assertEquals(2, tx.getInputs().size()); assertEquals(2, tx.getOutputs().size()); TransactionInput txIn0 = tx.getInput(0); TransactionInput txIn1 = tx.getInput(1); ECKey key0 = ECKey.fromPrivate(ByteUtils.parseHex("bbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866")); Script scriptPubKey0 = ScriptBuilder.createP2PKOutputScript(key0); assertEquals("2103c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432ac", ByteUtils.formatHex(scriptPubKey0.program())); ECKey key1 = ECKey.fromPrivate(ByteUtils.parseHex("619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9")); assertEquals("025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357", key1.getPublicKeyAsHex()); Script scriptPubKey1 = ScriptBuilder.createP2WPKHOutputScript(key1); assertEquals("00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1", ByteUtils.formatHex(scriptPubKey1.program())); txIn1.connect(new Transaction().addOutput(Coin.COIN.multiply(6), scriptPubKey1)); assertEquals("63cec688ee06a91e913875356dd4dea2f8e0f2a2659885372da2a37e32c7532e", tx.hashForSignature(0, scriptPubKey0, Transaction.SigHash.ALL, false).toString()); TransactionSignature txSig0 = tx.calculateSignature(0, key0, scriptPubKey0, Transaction.SigHash.ALL, false); assertEquals("30450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01", ByteUtils.formatHex(txSig0.encodeToBitcoin())); Script witnessScript = ScriptBuilder.createP2PKHOutputScript(key1); assertEquals("76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac", ByteUtils.formatHex(witnessScript.program())); assertEquals("c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670", tx.hashForWitnessSignature(1, witnessScript, txIn1.getValue(), Transaction.SigHash.ALL, false).toString()); TransactionSignature txSig1 = tx.calculateWitnessSignature(1, key1, witnessScript, txIn1.getValue(), Transaction.SigHash.ALL, false); assertEquals("304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee" + "01", ByteUtils.formatHex(txSig1.encodeToBitcoin())); assertFalse(correctlySpends(txIn0, scriptPubKey0, 0)); txIn0.setScriptSig(new ScriptBuilder().data(txSig0.encodeToBitcoin()).build()); assertTrue(correctlySpends(txIn0, scriptPubKey0, 0)); assertFalse(correctlySpends(txIn1, scriptPubKey1, 1)); txIn1.setWitness(TransactionWitness.redeemP2WPKH(txSig1, key1)); // no redeem script for p2wpkh assertTrue(correctlySpends(txIn1, scriptPubKey1, 1)); String signedTxHex = "01000000" // version + "00" // marker + "01" // flag + "02" // num txIn + "fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f" + "00000000" + "494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01" + "eeffffff" // txIn + "ef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a" + "01000000" + "00" + "ffffffff" // txIn + "02" // num txOut + "202cb20600000000" + "1976a914" + "8280b37df378db99f66f85c95a783a76ac7a6d59" + "88ac" // txOut + "9093510d00000000" + "1976a914" + "3bde42dbee7e4dbe6a21b2d50ce2f0167faa8159" + "88ac" // txOut + "00" // witness (empty) + "02" // witness (2 pushes) + "47" // push length + "304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee01" // push + "21" // push length + "025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357" // push + "11000000"; // nLockTime assertEquals(signedTxHex, ByteUtils.formatHex(tx.serialize())); assertEquals(signedTxHex.length() / 2, tx.messageSize()); } @Test public void testWitnessSignatureP2SH_P2WPKH() { // test vector P2SH-P2WPKH from: // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki String txHex = "01000000" // version + "01" // num txIn + "db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a5477" + "01000000" + "00" + "feffffff" // txIn + "02" // num txOut + "b8b4eb0b00000000" + "1976a914" + "a457b684d7f0d539a46a45bbc043f35b59d0d963" + "88ac" // txOut + "0008af2f00000000" + "1976a914" + "fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c" + "88ac" // txOut + "92040000"; // nLockTime Transaction tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(txHex))); assertEquals(txHex, ByteUtils.formatHex(tx.serialize())); assertEquals(txHex.length() / 2, tx.messageSize()); assertEquals(1, tx.getInputs().size()); assertEquals(2, tx.getOutputs().size()); TransactionInput txIn = tx.getInput(0); ECKey key = ECKey.fromPrivate( ByteUtils.parseHex("eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf")); assertEquals("03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873", key.getPublicKeyAsHex()); Script redeemScript = ScriptBuilder.createP2WPKHOutputScript(key); assertEquals("001479091972186c449eb1ded22b78e40d009bdf0089", ByteUtils.formatHex(redeemScript.program())); byte[] p2wpkhHash = CryptoUtils.sha256hash160(redeemScript.program()); Script scriptPubKey = ScriptBuilder.createP2SHOutputScript(p2wpkhHash); assertEquals("a9144733f37cf4db86fbc2efed2500b4f4e49f31202387", ByteUtils.formatHex(scriptPubKey.program())); Script witnessScript = ScriptBuilder.createP2PKHOutputScript(key); assertEquals("76a91479091972186c449eb1ded22b78e40d009bdf008988ac", ByteUtils.formatHex(witnessScript.program())); assertEquals("64f3b0f4dd2bb3aa1ce8566d220cc74dda9df97d8490cc81d89d735c92e59fb6", tx.hashForWitnessSignature(0, witnessScript, Coin.COIN.multiply(10), Transaction.SigHash.ALL, false) .toString()); TransactionSignature txSig = tx.calculateWitnessSignature(0, key, witnessScript, Coin.COIN.multiply(10), Transaction.SigHash.ALL, false); assertEquals("3044022047ac8e878352d3ebbde1c94ce3a10d057c24175747116f8288e5d794d12d482f0220217f36a485cae903c713331d877c1f64677e3622ad4010726870540656fe9dcb" + "01", ByteUtils.formatHex(txSig.encodeToBitcoin())); assertFalse(correctlySpends(txIn, scriptPubKey, 0)); txIn.setWitness(TransactionWitness.redeemP2WPKH(txSig, key)); txIn.setScriptSig(new ScriptBuilder().data(redeemScript.program()).build()); assertTrue(correctlySpends(txIn, scriptPubKey, 0)); String signedTxHex = "01000000" // version + "00" // marker + "01" // flag + "01" // num txIn + "db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a5477" + "01000000" // txIn + "1716001479091972186c449eb1ded22b78e40d009bdf0089" + "feffffff" // txIn + "02" // num txOut + "b8b4eb0b00000000" + "1976a914" + "a457b684d7f0d539a46a45bbc043f35b59d0d963" + "88ac" // txOut + "0008af2f00000000" + "1976a914" + "fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c" + "88ac" // txOut + "02" // witness (2 pushes) + "47" // push length + "3044022047ac8e878352d3ebbde1c94ce3a10d057c24175747116f8288e5d794d12d482f0220217f36a485cae903c713331d877c1f64677e3622ad4010726870540656fe9dcb01" // push + "21" // push length + "03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873" // push + "92040000"; // nLockTime assertEquals(signedTxHex, ByteUtils.formatHex(tx.serialize())); assertEquals(signedTxHex.length() / 2, tx.messageSize()); } @Test public void testWitnessSignatureP2SH_P2WSHSingleAnyoneCanPay() throws Exception { // test vector P2SH-P2WSH from the final example at: // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#p2sh-p2wsh String txHex = "01000000" // version + "01" // num txIn + "36641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e" + "01000000" + "00" + "ffffffff" // txIn + "02" // num txOut + "00e9a43500000000" + "1976a914" + "389ffce9cd9ae88dcc0631e88a821ffdbe9bfe26" + "88ac" // txOut + "c0832f0500000000" + "1976a914" + "7480a33f950689af511e6e84c138dbbd3c3ee415" + "88ac" // txOut + "00000000"; // nLockTime Transaction tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(txHex))); ECKey pubKey = ECKey.fromPublicOnly(ByteUtils.parseHex( "02d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b")); Script script = Script.parse(ByteUtils.parseHex( "56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae")); Sha256Hash hash = tx.hashForWitnessSignature(0, script, Coin.valueOf(987654321L), Transaction.SigHash.SINGLE, true); TransactionSignature signature = TransactionSignature.decodeFromBitcoin(ByteUtils.parseHex( "30440220525406a1482936d5a21888260dc165497a90a15669636d8edca6b9fe490d309c022032af0c646a34a44d1f4576bf6a4a74b67940f8faa84c7df9abe12a01a11e2b4783"), true, true); assertTrue(pubKey.verify(hash, signature)); } private boolean correctlySpends(TransactionInput txIn, Script scriptPubKey, int inputIndex) { try { txIn.getScriptSig().correctlySpends(txIn.getParentTransaction(), inputIndex, txIn.getWitness(), txIn.getValue(), scriptPubKey, Script.ALL_VERIFY_FLAGS); return true; } catch (ScriptException x) { return false; } } @Test public void testToString() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); int lengthWithAddresses = tx.toString(null, BitcoinNetwork.TESTNET).length(); int lengthWithoutAddresses = tx.toString(null, null).length(); assertTrue(lengthWithAddresses > lengthWithoutAddresses); } @Test public void testToStringWhenLockTimeIsSpecifiedInBlockHeight() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); TransactionInput input = tx.getInput(0); input.setSequenceNumber(42); int TEST_LOCK_TIME = 20; tx.setLockTime(TEST_LOCK_TIME); Calendar cal = Calendar.getInstance(); cal.set(2085, 10, 4, 17, 53, 21); cal.set(Calendar.MILLISECOND, 0); BlockChain mockBlockChain = createMock(BlockChain.class); EasyMock.expect(mockBlockChain.estimateBlockTimeInstant(TEST_LOCK_TIME)).andReturn(Instant.ofEpochMilli(cal.getTimeInMillis())); replay(mockBlockChain); String str = tx.toString(mockBlockChain, BitcoinNetwork.TESTNET); assertTrue(str.contains("block " + TEST_LOCK_TIME)); assertTrue(str.contains("estimated to be reached at")); } @Test public void testToStringWhenIteratingOverAnInputCatchesAnException() { Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); TransactionInput ti = new TransactionInput(tx, new byte[0], TransactionOutPoint.UNCONNECTED) { @Override public Script getScriptSig() throws ScriptException { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, ""); } }; tx.addInput(ti); assertTrue(tx.toString().contains("[exception: ")); } @Test public void testToStringWhenThereAreZeroInputs() { Transaction tx = new Transaction(); assertTrue(tx.toString().contains("No inputs!")); } @Test public void testTheTXByHeightComparator() { Transaction tx1 = FakeTxBuilder.createFakeTx(TESTNET.network()); tx1.getConfidence().setAppearedAtChainHeight(1); Transaction tx2 = FakeTxBuilder.createFakeTx(TESTNET.network()); tx2.getConfidence().setAppearedAtChainHeight(2); Transaction tx3 = FakeTxBuilder.createFakeTx(TESTNET.network()); tx3.getConfidence().setAppearedAtChainHeight(3); SortedSet<Transaction> set = new TreeSet<>(Transaction.SORT_TX_BY_HEIGHT); set.add(tx2); set.add(tx1); set.add(tx3); Iterator<Transaction> iterator = set.iterator(); assertFalse(tx1.equals(tx2)); assertFalse(tx1.equals(tx3)); assertTrue(tx1.equals(tx1)); assertTrue(iterator.next().equals(tx3)); assertTrue(iterator.next().equals(tx2)); assertTrue(iterator.next().equals(tx1)); assertFalse(iterator.hasNext()); } @Test(expected = ScriptException.class) public void testAddSignedInputThrowsExceptionWhenScriptIsNotToRawPubKeyAndIsNotToAddress() { ECKey key = new ECKey(); Address addr = key.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); TransactionOutput fakeOutput = FakeTxBuilder.createFakeTx(TESTNET.network(), Coin.COIN, addr).getOutput(0); Transaction tx = new Transaction(); tx.addOutput(fakeOutput); Script script = ScriptBuilder.createOpReturnScript(new byte[0]); tx.addSignedInput(fakeOutput.getOutPointFor(), script, fakeOutput.getValue(), key); } @Test public void testPrioSizeCalc() { Transaction tx1 = FakeTxBuilder.createFakeTx(TESTNET.network(), Coin.COIN, ADDRESS); int size1 = tx1.messageSize(); int size2 = tx1.getMessageSizeForPriorityCalc(); assertEquals(113, size1 - size2); tx1.getInput(0).setScriptSig(Script.parse(new byte[109])); assertEquals(78, tx1.getMessageSizeForPriorityCalc()); tx1.getInput(0).setScriptSig(Script.parse(new byte[110])); assertEquals(78, tx1.getMessageSizeForPriorityCalc()); tx1.getInput(0).setScriptSig(Script.parse(new byte[111])); assertEquals(79, tx1.getMessageSizeForPriorityCalc()); } @Test public void testCoinbaseHeightCheck() { // Coinbase transaction from block 300,000 ByteBuffer transactionBytes = ByteBuffer.wrap(ByteUtils.parseHex( "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4803e09304062f503253482f0403c86d53087ceca141295a00002e522cfabe6d6d7561cf262313da1144026c8f7a43e3899c44f6145f39a36507d36679a8b7006104000000000000000000000001c8704095000000001976a91480ad90d403581fa3bf46086a91b2d9d4125db6c188ac00000000")); final int height = 300000; final Transaction transaction = TESTNET.getDefaultSerializer().makeTransaction(transactionBytes); transaction.checkCoinBaseHeight(height); } /** * Test a coinbase transaction whose script has nonsense after the block height. * See https://github.com/bitcoinj/bitcoinj/issues/1097 */ @Test public void testCoinbaseHeightCheckWithDamagedScript() { // Coinbase transaction from block 224,430 ByteBuffer transactionBytes = ByteBuffer.wrap(ByteUtils.parseHex( "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff3b03ae6c0300044bd7031a0400000000522cfabe6d6d00000000000000b7b8bf0100000068692066726f6d20706f6f6c7365727665726aac1eeeed88ffffffff01e0587597000000001976a91421c0d001728b3feaf115515b7c135e779e9f442f88ac00000000")); final int height = 224430; final Transaction transaction = TESTNET.getDefaultSerializer().makeTransaction(transactionBytes); transaction.checkCoinBaseHeight(height); } @Test public void optInFullRBF() { // a standard transaction as wallets would create Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); assertFalse(tx.isOptInFullRBF()); tx.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 2); assertTrue(tx.isOptInFullRBF()); } /** * Ensure that hashForSignature() doesn't modify a transaction's data, which could wreak multithreading havoc. */ @Test public void testHashForSignatureThreadSafety() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); Block genesis = TESTNET.getGenesisBlock(); Block block1 = genesis.createNextBlock(new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), genesis.getTransactions().get(0).getOutput(0).getOutPointFor()); final Transaction tx = block1.getTransactions().get(1); final Sha256Hash txHash = tx.getTxId(); final String txNormalizedHash = tx.hashForSignature( 0, new byte[0], Transaction.SigHash.ALL.byteValue()) .toString(); final Runnable runnable = () -> { // ensure the transaction object itself was not modified; if it was, the hash will change assertEquals(txHash, tx.getTxId()); assertEquals( txNormalizedHash, tx.hashForSignature( 0, new byte[0], Transaction.SigHash.ALL.byteValue()) .toString()); assertEquals(txHash, tx.getTxId()); }; final int nThreads = 100; ExecutorService executor = Executors.newFixedThreadPool(nThreads); // do our best to run as parallel as possible // Build a stream of nThreads CompletableFutures and convert to an array CompletableFuture<Void>[] results = Stream .generate(() -> CompletableFuture.runAsync(runnable, executor)) .limit(nThreads) .toArray(genericArray(CompletableFuture[]::new)); executor.shutdown(); CompletableFuture.allOf(results).get(); // we're just interested in the exception, if any } /** * Function used to create/cast generic array to expected type. Using this function prevents us from * needing a {@code @SuppressWarnings("unchecked")} in the calling code. * @param arrayCreator Array constructor lambda taking an integer size parameter and returning array of type T * @param <T> The erased type * @param <R> The desired type * @return Array constructor lambda taking an integer size parameter and returning array of type R */ @SuppressWarnings("unchecked") static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) { return size -> (R[]) arrayCreator.apply(size); } @Test public void parseTransactionWithHugeDeclaredInputsSize() { Transaction tx = new HugeDeclaredSizeTransaction(true, false, false); byte[] serializedTx = tx.serialize(); try { Transaction.read(ByteBuffer.wrap(serializedTx)); fail("We expect BufferUnderflowException with the fixed code and OutOfMemoryError with the buggy code, so this is weird"); } catch (BufferUnderflowException e) { //Expected, do nothing } } @Test public void parseTransactionWithHugeDeclaredOutputsSize() { Transaction tx = new HugeDeclaredSizeTransaction(false, true, false); byte[] serializedTx = tx.serialize(); try { Transaction.read(ByteBuffer.wrap(serializedTx)); fail("We expect BufferUnderflowException with the fixed code and OutOfMemoryError with the buggy code, so this is weird"); } catch (BufferUnderflowException e) { //Expected, do nothing } } @Test public void parseTransactionWithHugeDeclaredWitnessPushCountSize() { Transaction tx = new HugeDeclaredSizeTransaction(false, false, true); byte[] serializedTx = tx.serialize(); try { Transaction.read(ByteBuffer.wrap(serializedTx)); fail("We expect BufferUnderflowException with the fixed code and OutOfMemoryError with the buggy code, so this is weird"); } catch (BufferUnderflowException e) { //Expected, do nothing } } private static class HugeDeclaredSizeTransaction extends Transaction { private boolean hackInputsSize; private boolean hackOutputsSize; private boolean hackWitnessPushCountSize; public HugeDeclaredSizeTransaction(boolean hackInputsSize, boolean hackOutputsSize, boolean hackWitnessPushCountSize) { super(); Transaction inputTx = new Transaction(); inputTx.addOutput(Coin.FIFTY_COINS, new ECKey()); this.addInput(inputTx.getOutput(0)); this.getInput(0).disconnect(); TransactionWitness witness = TransactionWitness.of(new byte[] { 0 }); this.getInput(0).setWitness(witness); this.addOutput(Coin.COIN, new ECKey()); this.hackInputsSize = hackInputsSize; this.hackOutputsSize = hackOutputsSize; this.hackWitnessPushCountSize = hackWitnessPushCountSize; } @Override protected void bitcoinSerializeToStream(OutputStream stream, boolean useSegwit) throws IOException { // version writeInt32LE(getVersion(), stream); // marker, flag if (useSegwit) { stream.write(0); stream.write(1); } // txin_count, txins long inputsSize = hackInputsSize ? Integer.MAX_VALUE : getInputs().size(); stream.write(VarInt.of(inputsSize).serialize()); for (TransactionInput in : getInputs()) stream.write(in.serialize()); // txout_count, txouts long outputsSize = hackOutputsSize ? Integer.MAX_VALUE : getOutputs().size(); stream.write(VarInt.of(outputsSize).serialize()); for (TransactionOutput out : getOutputs()) stream.write(out.serialize()); // script_witnisses if (useSegwit) { for (TransactionInput in : getInputs()) { TransactionWitness witness = in.getWitness(); long pushCount = hackWitnessPushCountSize ? Integer.MAX_VALUE : witness.getPushCount(); stream.write(VarInt.of(pushCount).serialize()); for (int i = 0; i < witness.getPushCount(); i++) { byte[] push = witness.getPush(i); stream.write(VarInt.of(push.length).serialize()); stream.write(push); } stream.write(in.getWitness().serialize()); } } // lock_time writeInt32LE(lockTime().rawValue(), stream); } } @Test public void getWeightAndVsize() { // example from https://en.bitcoin.it/wiki/Weight_units String txHex = "0100000000010115e180dc28a2327e687facc33f10f2a20da717e5548406f7ae8b4c811072f85603000000171600141d7cd6c75c2e86f4cbf98eaed221b30bd9a0b928ffffffff019caef505000000001976a9141d7cd6c75c2e86f4cbf98eaed221b30bd9a0b92888ac02483045022100f764287d3e99b1474da9bec7f7ed236d6c81e793b20c4b5aa1f3051b9a7daa63022016a198031d5554dbb855bdbe8534776a4be6958bd8d530dc001c32b828f6f0ab0121038262a6c6cec93c2d3ecd6c6072efea86d02ff8e3328bbd0242b20af3425990ac00000000"; Transaction tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(txHex))); assertEquals(218, tx.messageSize()); assertEquals(542, tx.getWeight()); assertEquals(136, tx.getVsize()); } @Test public void nonSegwitZeroInputZeroOutputTx() { // Non segwit tx with zero input and outputs String txHex = "010000000000f1f2f3f4"; Transaction tx = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex(txHex))); assertEquals(txHex, ByteUtils.formatHex(tx.serialize())); } @Test public void nonSegwitZeroInputOneOutputTx() { // Non segwit tx with zero input and one output that has an amount of `0100000000000000` that could confuse // a naive segwit parser. This can only be read with segwit disabled MessageSerializer serializer = TESTNET.getDefaultSerializer(); String txHex = "0100000000010100000000000000016af1f2f3f4"; int protoVersionNoWitness = serializer.getProtocolVersion() | Transaction.SERIALIZE_TRANSACTION_NO_WITNESS; Transaction tx = serializer.withProtocolVersion(protoVersionNoWitness).makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex(txHex))); assertEquals(txHex, ByteUtils.formatHex(tx.serialize())); } }
40,739
50.309824
1,321
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/ParseByteCacheTest.java
/* * Copyright 2011 Steve Coughlan. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.wallet.Wallet; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.valueOf; import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock; import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class ParseByteCacheTest { private static final int BLOCK_HEIGHT_GENESIS = 0; private final byte[] txMessage = ByteUtils.parseHex( "f9beb4d974780000000000000000000002010000e293cdbe01000000016dbddb085b1d8af75184f0bc01fad58d1266e9b63b50881990e4b40d6aee3629000000008b483045022100f3581e1972ae8ac7c7367a7a253bc1135223adb9a468bb3a59233f45bc578380022059af01ca17d00e41837a1d58e97aa31bae584edec28d35bd96923690913bae9a0141049c02bfc97ef236ce6d8fe5d94013c721e915982acd2b12b65d9b7d59e20a842005f8fc4e02532e873d37b96f09d6d4511ada8f14042f46614a4c70c0f14beff5ffffffff02404b4c00000000001976a9141aa0cd1cbea6e7458a7abad512a9d9ea1afb225e88ac80fae9c7000000001976a9140eab5bea436a0484cfab12485efda0b78b4ecc5288ac00000000"); private final byte[] txMessagePart = ByteUtils.parseHex( "085b1d8af75184f0bc01fad58d1266e9b63b50881990e4b40d6aee3629000000008b483045022100f3581e1972ae8ac7c7367a7a253bc1135223adb9a468bb3a"); private BlockStore blockStore; private byte[] b1Bytes; private byte[] b1BytesWithHeader; private byte[] tx1Bytes; private byte[] tx1BytesWithHeader; private byte[] tx2Bytes; private byte[] tx2BytesWithHeader; private static final NetworkParameters TESTNET = TestNet3Params.get(); private static final NetworkParameters MAINNET = MainNetParams.get(); private void resetBlockStore() { blockStore = new MemoryBlockStore(TESTNET.getGenesisBlock()); } @Before public void setUp() throws Exception { TimeUtils.setMockClock(); // Use mock clock Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); wallet.freshReceiveKey(); resetBlockStore(); Transaction tx1 = createFakeTx(TESTNET.network(), valueOf(2, 0), wallet.currentReceiveKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); // add a second input so can test granularity of byte cache. Transaction prevTx = new Transaction(); TransactionOutput prevOut = new TransactionOutput(prevTx, COIN, wallet.currentReceiveKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); prevTx.addOutput(prevOut); // Connect it. tx1.addInput(prevOut); Transaction tx2 = createFakeTx(TESTNET.network(), COIN, new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); Block b1 = createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS, tx1, tx2).block; MessageSerializer serializer = TESTNET.getDefaultSerializer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializer.serialize(tx1, bos); tx1BytesWithHeader = bos.toByteArray(); tx1Bytes = tx1.serialize(); bos.reset(); serializer.serialize(tx2, bos); tx2BytesWithHeader = bos.toByteArray(); tx2Bytes = tx2.serialize(); bos.reset(); serializer.serialize(b1, bos); b1BytesWithHeader = bos.toByteArray(); b1Bytes = b1.serialize(); } @Test public void validateSetup() { byte[] b1 = {1, 1, 1, 2, 3, 4, 5, 6, 7}; byte[] b2 = {1, 2, 3}; assertTrue(arrayContains(b1, b2)); assertTrue(arrayContains(txMessage, txMessagePart)); assertTrue(arrayContains(tx1BytesWithHeader, tx1Bytes)); assertTrue(arrayContains(tx2BytesWithHeader, tx2Bytes)); assertTrue(arrayContains(b1BytesWithHeader, b1Bytes)); assertTrue(arrayContains(b1BytesWithHeader, tx1Bytes)); assertTrue(arrayContains(b1BytesWithHeader, tx2Bytes)); assertFalse(arrayContains(tx1BytesWithHeader, b1Bytes)); } @Test public void testTransactions() throws Exception { testTransaction(MAINNET, txMessage, false); testTransaction(TESTNET, tx1BytesWithHeader, false); testTransaction(TESTNET, tx2BytesWithHeader, false); } @Test public void testBlockAll() throws Exception { testBlock(b1BytesWithHeader, false); } public void testBlock(byte[] blockBytes, boolean isChild) throws Exception { // reference serializer to produce comparison serialization output after changes to // message structure. MessageSerializer serializerRef = TESTNET.getSerializer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); BitcoinSerializer serializer = TESTNET.getSerializer(); Block b1; Block bRef; b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // verify our reference BitcoinSerializer produces matching byte array. bos.reset(); serializerRef.serialize(bRef, bos); assertArrayEquals(bos.toByteArray(), blockBytes); // check retain status survive both before and after a serialization // "retained mode" was removed from Message, so maybe this test doesn't make much sense any more serDeser(serializer, b1, blockBytes, null, null); // compare to ref block bos.reset(); serializerRef.serialize(bRef, bos); serDeser(serializer, b1, bos.toByteArray(), null, null); // retrieve a value from a child b1.getTransactions(); if (b1.getTransactions().size() > 0) { Transaction tx1 = b1.getTransactions().get(0); // does it still match ref block? serDeser(serializer, b1, bos.toByteArray(), null, null); } // refresh block b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // retrieve a value from header b1.getDifficultyTarget(); // does it still match ref block? serDeser(serializer, b1, bos.toByteArray(), null, null); // refresh block b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // retrieve a value from a child and header b1.getDifficultyTarget(); b1.getTransactions(); if (b1.getTransactions().size() > 0) { Transaction tx1 = b1.getTransactions().get(0); } // does it still match ref block? serDeser(serializer, b1, bos.toByteArray(), null, null); // refresh block b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // change a value in header b1.setNonce(23); bRef.setNonce(23); // does it still match ref block? bos.reset(); serializerRef.serialize(bRef, bos); serDeser(serializer, b1, bos.toByteArray(), null, null); // refresh block b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // retrieve a value from a child of a child b1.getTransactions(); if (b1.getTransactions().size() > 0) { Transaction tx1 = b1.getTransactions().get(0); TransactionInput tin = tx1.getInput(0); // does it still match ref tx? bos.reset(); serializerRef.serialize(bRef, bos); serDeser(serializer, b1, bos.toByteArray(), null, null); } // refresh block b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // add an input b1.getTransactions(); if (b1.getTransactions().size() > 0) { Transaction tx1 = b1.getTransactions().get(0); if (tx1.getInputs().size() > 0) { tx1.addInput(tx1.getInput(0)); // replicate on reference tx bRef.getTransactions().get(0).addInput(bRef.getTransactions().get(0).getInput(0)); bos.reset(); serializerRef.serialize(bRef, bos); byte[] source = bos.toByteArray(); // confirm we still match the reference tx. serDeser(serializer, b1, source, null, null); } // does it still match ref tx? bos.reset(); serializerRef.serialize(bRef, bos); serDeser(serializer, b1, bos.toByteArray(), null, null); } // refresh block b1 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); Block b2 = (Block) serializer.deserialize(ByteBuffer.wrap(blockBytes)); bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); Block bRef2 = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); // reparent an input b1.getTransactions(); if (b1.getTransactions().size() > 0) { Transaction tx1 = b1.getTransactions().get(0); Transaction tx2 = b2.getTransactions().get(0); if (tx1.getInputs().size() > 0) { TransactionInput fromTx1 = tx1.getInput(0); tx2.addInput(fromTx1); // replicate on reference tx TransactionInput fromTxRef = bRef.getTransactions().get(0).getInput(0); bRef2.getTransactions().get(0).addInput(fromTxRef); bos.reset(); serializerRef.serialize(bRef2, bos); byte[] source = bos.toByteArray(); // confirm altered block matches altered ref block. serDeser(serializer, b2, source, null, null); } // does unaltered block still match ref block? bos.reset(); serializerRef.serialize(bRef, bos); serDeser(serializer, b1, bos.toByteArray(), null, null); // how about if we refresh it? bRef = (Block) serializerRef.deserialize(ByteBuffer.wrap(blockBytes)); bos.reset(); serializerRef.serialize(bRef, bos); serDeser(serializer, b1, bos.toByteArray(), null, null); } } public void testTransaction(NetworkParameters params, byte[] txBytes, boolean isChild) throws Exception { // reference serializer to produce comparison serialization output after changes to // message structure. MessageSerializer serializerRef = params.getSerializer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); BitcoinSerializer serializer = params.getSerializer(); Transaction t1; Transaction tRef; t1 = (Transaction) serializer.deserialize(ByteBuffer.wrap(txBytes)); tRef = (Transaction) serializerRef.deserialize(ByteBuffer.wrap(txBytes)); // verify our reference BitcoinSerializer produces matching byte array. bos.reset(); serializerRef.serialize(tRef, bos); assertArrayEquals(bos.toByteArray(), txBytes); // check and retain status survive both before and after a serialization // "retained mode" was removed from Message, so maybe this test doesn't make much sense any more serDeser(serializer, t1, txBytes, null, null); // compare to ref tx bos.reset(); serializerRef.serialize(tRef, bos); serDeser(serializer, t1, bos.toByteArray(), null, null); // retrieve a value from a child t1.getInputs(); if (t1.getInputs().size() > 0) { TransactionInput tin = t1.getInput(0); // does it still match ref tx? serDeser(serializer, t1, bos.toByteArray(), null, null); } // refresh tx t1 = (Transaction) serializer.deserialize(ByteBuffer.wrap(txBytes)); tRef = (Transaction) serializerRef.deserialize(ByteBuffer.wrap(txBytes)); // add an input if (t1.getInputs().size() > 0) { t1.addInput(t1.getInput(0)); // replicate on reference tx tRef.addInput(tRef.getInput(0)); bos.reset(); serializerRef.serialize(tRef, bos); byte[] source = bos.toByteArray(); //confirm we still match the reference tx. serDeser(serializer, t1, source, null, null); } } private void serDeser(MessageSerializer serializer, Message message, byte[] sourceBytes, byte[] containedBytes, byte[] containingBytes) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializer.serialize(message, bos); byte[] b1 = bos.toByteArray(); Message m2 = serializer.deserialize(ByteBuffer.wrap(b1)); assertEquals(message, m2); bos.reset(); serializer.serialize(m2, bos); byte[] b2 = bos.toByteArray(); assertArrayEquals(b1, b2); if (sourceBytes != null) { assertTrue(arrayContains(sourceBytes, b1)); assertTrue(arrayContains(sourceBytes, b2)); } if (containedBytes != null) { assertTrue(arrayContains(b1, containedBytes)); } if (containingBytes != null) { assertTrue(arrayContains(containingBytes, b1)); } } // Determine if sub is contained in sup. public static boolean arrayContains(byte[] sup, byte[] sub) { ByteBuffer subBuf = ByteBuffer.wrap(sub); int subLength = sub.length; int lengthDiff = sup.length - subLength; if (lengthDiff < 0) return false; for (int i = 0; i <= lengthDiff; i++) if (ByteBuffer.wrap(sup, i, subLength).equals(subBuf)) return true; return false; } @Test public void testArrayContains() { byte[] oneToNine = ByteUtils.parseHex("010203040506070809"); assertTrue(arrayContains(oneToNine, oneToNine)); assertTrue(arrayContains(oneToNine, ByteUtils.parseHex("010203"))); assertTrue(arrayContains(oneToNine, ByteUtils.parseHex("040506"))); assertTrue(arrayContains(oneToNine, ByteUtils.parseHex("070809"))); assertTrue(arrayContains(oneToNine, new byte[0])); assertFalse(arrayContains(oneToNine, ByteUtils.parseHex("123456"))); assertFalse(arrayContains(oneToNine, ByteUtils.parseHex("080910"))); assertFalse(arrayContains(oneToNine, ByteUtils.parseHex("01020304050607080910"))); } }
16,494
39.628079
580
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/PeerAddressTest.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.params.MainNetParams; import org.junit.Test; import org.junit.runner.RunWith; import java.math.BigInteger; import java.net.InetAddress; import java.nio.ByteBuffer; import java.time.Instant; import java.time.temporal.ChronoUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(JUnitParamsRunner.class) public class PeerAddressTest { private static final NetworkParameters MAINNET = MainNetParams.get(); @Test public void equalsContract() { EqualsVerifier.forClass(PeerAddress.class) .suppress(Warning.NONFINAL_FIELDS) .withIgnoredFields("time") .usingGetClass() .verify(); } @Test public void roundtrip_ipv4_addressV2Variant() throws Exception { Instant time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); PeerAddress pa = PeerAddress.inet(InetAddress.getByName("1.2.3.4"), 1234, Services.none(), time); byte[] serialized = pa.serialize(2); PeerAddress pa2 = PeerAddress.read(ByteBuffer.wrap(serialized), 2); assertEquals("1.2.3.4", pa2.getAddr().getHostAddress()); assertEquals(1234, pa2.getPort()); assertEquals(Services.none(), pa2.getServices()); assertTrue(pa2.time().compareTo(time) >= 0 && pa2.time().isBefore(time.plusSeconds(5)));// potentially racy } @Test public void roundtrip_ipv4_addressVariant() throws Exception { Instant time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); PeerAddress pa = PeerAddress.inet(InetAddress.getByName("1.2.3.4"), 1234, Services.none(), time); byte[] serialized = pa.serialize(1); PeerAddress pa2 = PeerAddress.read(ByteBuffer.wrap(serialized), 1); assertEquals("1.2.3.4", pa2.getAddr().getHostAddress()); assertEquals(1234, pa2.getPort()); assertEquals(Services.none(), pa2.getServices()); assertTrue(pa2.time().compareTo(time) >= 0 && pa2.time().isBefore(time.plusSeconds(5))); // potentially racy } @Test public void roundtrip_ipv6_addressV2Variant() throws Exception { Instant time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); PeerAddress pa = PeerAddress.inet(InetAddress.getByName("2001:db8:85a3:0:0:8a2e:370:7334"), 1234, Services.none(), time); byte[] serialized = pa.serialize(2); PeerAddress pa2 = PeerAddress.read(ByteBuffer.wrap(serialized), 2); assertEquals("2001:db8:85a3:0:0:8a2e:370:7334", pa2.getAddr().getHostAddress()); assertEquals(1234, pa2.getPort()); assertEquals(Services.none(), pa2.getServices()); assertTrue(pa2.time().compareTo(time) >= 0 && pa2.time().isBefore(time.plusSeconds(5))); // potentially racy } @Test public void roundtrip_ipv6_addressVariant() throws Exception { Instant time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); PeerAddress pa = PeerAddress.inet(InetAddress.getByName("2001:db8:85a3:0:0:8a2e:370:7334"), 1234, Services.none(), time); byte[] serialized = pa.serialize(1); PeerAddress pa2 = PeerAddress.read(ByteBuffer.wrap(serialized), 1); assertEquals("2001:db8:85a3:0:0:8a2e:370:7334", pa2.getAddr().getHostAddress()); assertEquals(1234, pa2.getPort()); assertEquals(Services.none(), pa2.getServices()); assertTrue(pa2.time().compareTo(time) >= 0 && pa2.time().isBefore(time.plusSeconds(5))); // potentially racy } @Test @Parameters(method = "deserializeToStringValues") public void deserializeToString(int version, String expectedToString, String hex) { PeerAddress pa = PeerAddress.read(ByteBuffer.wrap(ByteUtils.parseHex(hex)), version); assertEquals(expectedToString, pa.toString()); } private Object[] deserializeToStringValues() { return new Object[]{ new Object[]{1, "[10.0.0.1]:8333", "00000000010000000000000000000000000000000000ffff0a000001208d"}, new Object[]{1, "[127.0.0.1]:8333", "00000000000000000000000000000000000000000000ffff7f000001208d"}, new Object[]{2, "[etj2w3zby7hfaldy34dsuttvjtimywhvqjitk3w75ufprsqe47vr6vyd.onion]:8333", "2b71fd62fd0d04042024d3ab6f21c7ce502c78df072a4e754cd0cc58f58251356edfed0af8ca04e7eb208d"}, new Object[]{2, "[ PeerAddress of unsupported type ]:8333", "2f29fa62fd0d040610fca6763db6183c48d0d58d902c80e1f2208d"} }; } }
5,438
44.705882
195
java
bitcoinj
bitcoinj-master/core/src/test/java/org/bitcoinj/core/BitcoinSerializerTest.java
/* * Copyright 2011 Noa Resare * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.io.BaseEncoding; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.net.InetAddress; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.time.temporal.ChronoUnit; import java.util.Arrays; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class BitcoinSerializerTest { private static final BaseEncoding HEX = BaseEncoding.base16().lowerCase(); private static final NetworkParameters MAINNET = MainNetParams.get(); private static final byte[] ADDRESS_MESSAGE_BYTES = ByteUtils.parseHex("f9beb4d96164647200000000000000001f000000" + "ed52399b01e215104d010000000000000000000000000000000000ffff0a000001208d"); private static final byte[] TRANSACTION_MESSAGE_BYTES = HEX.withSeparator(" ", 2).decode( "f9 be b4 d9 74 78 00 00 00 00 00 00 00 00 00 00" + "02 01 00 00 e2 93 cd be 01 00 00 00 01 6d bd db" + "08 5b 1d 8a f7 51 84 f0 bc 01 fa d5 8d 12 66 e9" + "b6 3b 50 88 19 90 e4 b4 0d 6a ee 36 29 00 00 00" + "00 8b 48 30 45 02 21 00 f3 58 1e 19 72 ae 8a c7" + "c7 36 7a 7a 25 3b c1 13 52 23 ad b9 a4 68 bb 3a" + "59 23 3f 45 bc 57 83 80 02 20 59 af 01 ca 17 d0" + "0e 41 83 7a 1d 58 e9 7a a3 1b ae 58 4e de c2 8d" + "35 bd 96 92 36 90 91 3b ae 9a 01 41 04 9c 02 bf" + "c9 7e f2 36 ce 6d 8f e5 d9 40 13 c7 21 e9 15 98" + "2a cd 2b 12 b6 5d 9b 7d 59 e2 0a 84 20 05 f8 fc" + "4e 02 53 2e 87 3d 37 b9 6f 09 d6 d4 51 1a da 8f" + "14 04 2f 46 61 4a 4c 70 c0 f1 4b ef f5 ff ff ff" + "ff 02 40 4b 4c 00 00 00 00 00 19 76 a9 14 1a a0" + "cd 1c be a6 e7 45 8a 7a ba d5 12 a9 d9 ea 1a fb" + "22 5e 88 ac 80 fa e9 c7 00 00 00 00 19 76 a9 14" + "0e ab 5b ea 43 6a 04 84 cf ab 12 48 5e fd a0 b7" + "8b 4e cc 52 88 ac 00 00 00 00"); @Test public void testAddr() throws Exception { MessageSerializer serializer = MAINNET.getDefaultSerializer(); // the actual data from https://en.bitcoin.it/wiki/Protocol_specification#addr AddressMessage addressMessage = (AddressMessage) serializer.deserialize(ByteBuffer.wrap(ADDRESS_MESSAGE_BYTES)); assertEquals(1, addressMessage.getAddresses().size()); PeerAddress peerAddress = addressMessage.getAddresses().get(0); assertEquals(8333, peerAddress.getPort()); assertEquals("10.0.0.1", peerAddress.getAddr().getHostAddress()); ByteArrayOutputStream bos = new ByteArrayOutputStream(ADDRESS_MESSAGE_BYTES.length); serializer.serialize(addressMessage, bos); assertEquals(31, addressMessage.messageSize()); addressMessage.addAddress(PeerAddress.inet(InetAddress.getLocalHost(), MAINNET.getPort(), Services.none(), TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS))); bos = new ByteArrayOutputStream(61); serializer.serialize(addressMessage, bos); assertEquals(61, addressMessage.messageSize()); addressMessage.removeAddress(0); bos = new ByteArrayOutputStream(31); serializer.serialize(addressMessage, bos); assertEquals(31, addressMessage.messageSize()); //this wont be true due to dynamic timestamps. //assertTrue(LazyParseByteCacheTest.arrayContains(bos.toByteArray(), addrMessage)); } @Test public void testCachedParsing() throws Exception { // "retained mode" was removed from Message, so maybe this test doesn't make much sense any more MessageSerializer serializer = MAINNET.getSerializer(); // first try writing to a fields to ensure uncaching and children are not affected Transaction transaction = (Transaction) serializer.deserialize(ByteBuffer.wrap(TRANSACTION_MESSAGE_BYTES)); assertNotNull(transaction); transaction.setLockTime(1); ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializer.serialize(transaction, bos); assertFalse(Arrays.equals(TRANSACTION_MESSAGE_BYTES, bos.toByteArray())); // now try writing to a child to ensure uncaching is propagated up to parent but not to siblings transaction = (Transaction) serializer.deserialize(ByteBuffer.wrap(TRANSACTION_MESSAGE_BYTES)); assertNotNull(transaction); transaction.getInput(0).setSequenceNumber(1); bos = new ByteArrayOutputStream(); serializer.serialize(transaction, bos); assertFalse(Arrays.equals(TRANSACTION_MESSAGE_BYTES, bos.toByteArray())); // deserialize/reserialize to check for equals. transaction = (Transaction) serializer.deserialize(ByteBuffer.wrap(TRANSACTION_MESSAGE_BYTES)); assertNotNull(transaction); bos = new ByteArrayOutputStream(); serializer.serialize(transaction, bos); assertArrayEquals(TRANSACTION_MESSAGE_BYTES, bos.toByteArray()); // deserialize/reserialize to check for equals. Set a field to it's existing value to trigger uncache transaction = (Transaction) serializer.deserialize(ByteBuffer.wrap(TRANSACTION_MESSAGE_BYTES)); assertNotNull(transaction); transaction.getInput(0).setSequenceNumber(transaction.getInputs().get(0).getSequenceNumber()); bos = new ByteArrayOutputStream(); serializer.serialize(transaction, bos); assertArrayEquals(TRANSACTION_MESSAGE_BYTES, bos.toByteArray()); } /** * Get 1 header of the block number 1 (the first one is 0) in the chain */ @Test public void testHeaders1() throws Exception { MessageSerializer serializer = MAINNET.getDefaultSerializer(); byte[] headersMessageBytes = ByteUtils.parseHex("f9beb4d9686561" + "646572730000000000520000005d4fab8101010000006fe28c0ab6f1b372c1a6a246ae6" + "3f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677b" + "a1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e3629900"); HeadersMessage headersMessage = (HeadersMessage) serializer.deserialize(ByteBuffer.wrap(headersMessageBytes)); // The first block after the genesis // http://blockexplorer.com/b/1 Block block = headersMessage.getBlockHeaders().get(0); assertEquals("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", block.getHashAsString()); assertNotNull(block.transactions); assertEquals("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098", ByteUtils.formatHex(block.getMerkleRoot().getBytes())); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); serializer.serialize(headersMessage, byteArrayOutputStream); byte[] serializedBytes = byteArrayOutputStream.toByteArray(); assertArrayEquals(headersMessageBytes, serializedBytes); } /** * Get 6 headers of blocks 1-6 in the chain */ @Test public void testHeaders2() throws Exception { MessageSerializer serializer = MAINNET.getDefaultSerializer(); byte[] headersMessageBytes = ByteUtils.parseHex("f9beb4d96865616465" + "72730000000000e701000085acd4ea06010000006fe28c0ab6f1b372c1a6a246ae63f74f931e" + "8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1c" + "db606e857233e0e61bc6649ffff001d01e3629900010000004860eb18bf1b1620e37e9490fc8a" + "427514416fd75159ab86688e9a8300000000d5fdcc541e25de1c7a5addedf24858b8bb665c9f36" + "ef744ee42c316022c90f9bb0bc6649ffff001d08d2bd610001000000bddd99ccfda39da1b108ce1" + "a5d70038d0a967bacb68b6b63065f626a0000000044f672226090d85db9a9f2fbfe5f0f9609b387" + "af7be5b7fbb7a1767c831c9e995dbe6649ffff001d05e0ed6d00010000004944469562ae1c2c74" + "d9a535e00b6f3e40ffbad4f2fda3895501b582000000007a06ea98cd40ba2e3288262b28638cec" + "5337c1456aaf5eedc8e9e5a20f062bdf8cc16649ffff001d2bfee0a9000100000085144a84488e" + "a88d221c8bd6c059da090e88f8a2c99690ee55dbba4e00000000e11c48fecdd9e72510ca84f023" + "370c9a38bf91ac5cae88019bee94d24528526344c36649ffff001d1d03e4770001000000fc33f5" + "96f822a0a1951ffdbf2a897b095636ad871707bf5d3162729b00000000379dfb96a5ea8c81700ea4" + "ac6b97ae9a9312b2d4301a29580e924ee6761a2520adc46649ffff001d189c4c9700"); HeadersMessage headersMessage = (HeadersMessage) serializer.deserialize(ByteBuffer.wrap(headersMessageBytes)); assertEquals(6, headersMessage.getBlockHeaders().size()); // index 0 block is the number 1 block in the block chain // http://blockexplorer.com/b/1 Block zeroBlock = headersMessage.getBlockHeaders().get(0); assertEquals("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048", zeroBlock.getHashAsString()); assertEquals(2573394689L, zeroBlock.getNonce()); // index 3 block is the number 4 block in the block chain // http://blockexplorer.com/b/4 Block thirdBlock = headersMessage.getBlockHeaders().get(3); assertEquals("000000004ebadb55ee9096c9a2f8880e09da59c0d68b1c228da88e48844a1485", thirdBlock.getHashAsString()); assertEquals(2850094635L, thirdBlock.getNonce()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); serializer.serialize(headersMessage, byteArrayOutputStream); byte[] serializedBytes = byteArrayOutputStream.toByteArray(); assertArrayEquals(headersMessageBytes, serializedBytes); } @Test(expected = BufferUnderflowException.class) public void testBitcoinPacketHeaderTooShort() { new BitcoinSerializer.BitcoinPacketHeader(ByteBuffer.wrap(new byte[] { 0 })); } @Test(expected = ProtocolException.class) public void testBitcoinPacketHeaderTooLong() { // Message with a Message size which is 1 too big, in little endian format. byte[] wrongMessageLength = ByteUtils.parseHex("000000000000000000000000010000020000000000"); new BitcoinSerializer.BitcoinPacketHeader(ByteBuffer.wrap(wrongMessageLength)); } @Test(expected = BufferUnderflowException.class) public void testSeekPastMagicBytes() { // Fail in another way, there is data in the stream but no magic bytes. byte[] brokenMessage = ByteUtils.parseHex("000000"); MAINNET.getDefaultSerializer().seekPastMagicBytes(ByteBuffer.wrap(brokenMessage)); } /** * Tests serialization of an unknown message. */ @Test(expected = Error.class) public void testSerializeUnknownMessage() throws Exception { MessageSerializer serializer = MAINNET.getDefaultSerializer(); Message unknownMessage = new BaseMessage() { @Override protected void bitcoinSerializeToStream(OutputStream stream) {} }; ByteArrayOutputStream bos = new ByteArrayOutputStream(ADDRESS_MESSAGE_BYTES.length); serializer.serialize(unknownMessage, bos); } @Test public void testEquals() { assertTrue(MAINNET.getDefaultSerializer().equals(MAINNET.getDefaultSerializer())); assertFalse(MAINNET.getDefaultSerializer().equals(TestNet3Params.get().getDefaultSerializer())); assertFalse(MAINNET.getDefaultSerializer().equals(MAINNET.getDefaultSerializer().withProtocolVersion(0))); } }
12,647
48.992095
144
java